Dart Maps in Depth
Maps gain methods that insert, change, and remove entries by rule. Each method takes a small function that decides the work.
Insert only when missing
The counter proves the builder runs once. The existing key keeps its old value, and the missing key gets the built one.
void main() {
var stock = {'pens': 4};
var built = 0;
var added = stock.putIfAbsent('rulers', () {
built++;
return 9;
});
var kept = stock.putIfAbsent('pens', () {
built++;
return 99;
});
print(added);
print(kept);
print(built);
print(stock);
}Change a value with update
The first update adds 5 to the stored value. The second update uses ifAbsent because the key is missing.
void main() {
var scores = {'Ana': 10, 'Ben': 20};
scores.update('Ana', (value) => value + 5);
scores.update('Cid', (value) => value + 5, ifAbsent: () => 5);
print(scores);
}Change every value with updateAll
updateAll hands each key and value to the function. Every value in the map is replaced by the result.
void main() {
var prices = {'pen': 2, 'book': 5};
prices.updateAll((key, value) => value * 10);
print(prices);
}Remove matches and merge maps
removeWhere drops every entry under 18. addAll then merges the second map, and its Ben value replaces the older one.
void main() {
var ages = {'Ana': 17, 'Ben': 25, 'Cid': 15, 'Dee': 30};
ages.removeWhere((key, value) => value < 18);
print(ages);
var extra = {'Eli': 40, 'Ben': 26};
ages.addAll(extra);
print(ages);
}Example
void main() {
var cart = {'apples': 2};
cart.putIfAbsent('apples', () => 10);
cart.putIfAbsent('pears', () => 3);
cart.update('apples', (value) => value + 1);
print(cart);
print(cart.length);
}Key points
- putIfAbsent adds a key only when the key is missing.
- The builder function of putIfAbsent runs only when the key is missing.
- update changes the value stored under an existing key.
- update takes an ifAbsent function for the case where the key is missing.
- updateAll changes every value in the map in place.
- removeWhere removes every entry that matches a test.
- addAll copies entries from another map, and a later value wins on a shared key.
In this example, putIfAbsent leaves the apples entry alone because the key exists. It adds pears with the value 3. The update then raises the apples count to 3, and the map holds two entries.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
A map holds {'pens': 4}. What does putIfAbsent('pens', () => 99) return?