Dart Maps
A Map<K, V> associates keys with values. Each key appears at most once. Maps are everywhere in Dart: configuration, caches, counting, and above all JSON data.
Creating maps
void main() {
var capitals = {
'Vietnam': 'Hanoi',
'Japan': 'Tokyo',
'Peru': 'Lima',
}; // Map<String, String>
Map<int, String> httpCodes = {200: 'OK', 404: 'Not Found'};
var empty = <String, int>{};
var fromLists = Map.fromIterables(['a', 'b'], [1, 2]);
print(capitals);
print(httpCodes[404]);
print(empty.isEmpty);
print(fromLists);
}{Vietnam: Hanoi, Japan: Tokyo, Peru: Lima}
Not Found
true
{a: 1, b: 2}
The default Map is a LinkedHashMap, so entries iterate in insertion order.
Reading values
The [] operator returns V? — nullable — because the key might be missing. Handle that explicitly:
void main() {
var stock = {'apple': 12, 'pear': 0};
int? apples = stock['apple'];
print(apples);
print(stock['kiwi']);
print(stock['kiwi'] ?? 0);
print(stock.containsKey('pear'));
print(stock.containsValue(12));
print(stock.keys);
print(stock.values);
print(stock.length);
}12
null
0
true
true
(apple, pear)
(12, 0)
2
Adding, updating and removing
| Method | Effect |
|---|---|
map[k] = v |
Insert or overwrite |
putIfAbsent(k, () => v) |
Insert only if missing; returns the value |
update(k, (old) => new, ifAbsent: () => v) |
Transform an existing value |
addAll(other) |
Copy all entries from another map |
remove(k) |
Delete, returns the old value or null |
removeWhere((k, v) => …) |
Delete matching entries |
void main() {
var cart = <String, int>{};
cart['coffee'] = 1;
cart['tea'] = 2;
cart['coffee'] = 3; // overwrite
cart.putIfAbsent('tea', () => 99); // tea exists: unchanged
cart.putIfAbsent('cake', () => 1);
cart.update('tea', (q) => q + 1);
cart.update('juice', (q) => q + 1, ifAbsent: () => 1);
print(cart);
print(cart.remove('cake'));
cart.removeWhere((item, qty) => qty > 2);
print(cart);
}{coffee: 3, tea: 3, cake: 1, juice: 1}
1
{juice: 1}
Iterating
void main() {
var scores = {'Lan': 91, 'Hung': 78, 'Thao': 85};
for (final name in scores.keys) {
print(name);
}
for (final MapEntry(key: name, value: score) in scores.entries) {
print('$name scored $score');
}
scores.forEach((name, score) => print('${name.padRight(5)}|${'#' * (score ~/ 10)}'));
var curved = scores.map((name, score) => MapEntry(name, score + 5));
print(curved);
}Lan
Hung
Thao
Lan scored 91
Hung scored 78
Thao scored 85
Lan |#########
Hung |#######
Thao |########
{Lan: 96, Hung: 83, Thao: 90}
Counting and grouping
Two patterns you'll write again and again:
void main() {
var text = 'the cat and the hat and the bat';
// word frequency
var counts = <String, int>{};
for (final w in text.split(' ')) {
counts[w] = (counts[w] ?? 0) + 1;
}
print(counts);
// group words by their length
var byLength = <int, List<String>>{};
for (final w in counts.keys) {
byLength.putIfAbsent(w.length, () => []).add(w);
}
print(byLength);
// sort entries by count, descending
var ranked = counts.entries.toList()
..sort((a, b) => b.value.compareTo(a.value));
print(ranked.first);
}{the: 3, cat: 1, and: 2, hat: 1, bat: 1}
{3: [the, cat, and, hat, bat]}
MapEntry(the: 3)
Tip: Need keys kept in sorted order?
SplayTreeMapfromdart:collectionsorts by key automatically.
Maps vs classes
Maps are flexible, but a Map<String, dynamic> loses type safety: a typo in a key compiles fine and returns null. For structured data with known fields, define a class or record and convert at the boundary (see JSON).
Test yourself
What is the static type of map['key'] for a Map<String, int>?
- int
- int?
- dynamic
- Object
Which call adds a key only when it is not already present?
- map.add(k, v)
- map.putIfAbsent(k, () => v)
- map.update(k, (_) => v)
- map.insert(k, v)
In what order does a default Dart map iterate its entries?
- Random order
- Sorted by key
- Insertion order
- Sorted by value