Sub topic 3
Maps: looking up values by key
A Map stores key-value pairs and finds a value from its key without scanning every entry. This chapter assumes you know basic Dart syntax, generic notation such as List<int>, and nullable types such as int?. It builds on the overview of the three core collections.
What a map is
A Map<K, V> associates each key of type K with one value of type V. Keys are unique. Assigning to a key that already exists replaces its value. Values can repeat freely.
A lookup does not compare your key against every stored key. The map computes the key's hashCode, jumps to the matching slot, and confirms with ==. For the built-in key types (String, int, bool, and so on) this makes lookup, insert, and removal take roughly constant time on average.
Creating maps
Use a literal with an explicit type when the map starts empty. Let inference work when the literal has entries.
void main() {
final ages = <String, int>{'Ana': 31, 'Ben': 27};
final empty = <String, int>{};
final inferred = {'a': 1, 'b': 2}; // Map<String, int>
final loose = {}; // Map<dynamic, dynamic>, usually not what you want
final fromPairs = Map<String, int>.fromEntries([MapEntry('x', 1)]);
final byLength = {
for (final w in ['kiwi', 'fig']) w: w.length,
};
print(ages); // {Ana: 31, Ben: 27}
print(empty.isEmpty); // true
print(inferred.runtimeType); // depends on the platform, a Map of String to int
print(loose.length); // 0
print(fromPairs); // {x: 1}
print(byLength); // {kiwi: 4, fig: 3}
}A bare {} is a map, not a set. To get an empty set you must write <int>{}. The untyped {} also becomes Map<dynamic, dynamic>, which turns off the type checks that make collections safe, so give it type arguments.
Reading and writing
Square brackets read and write. containsKey tests for a key. length, isEmpty, and isNotEmpty work as they do on lists.
void main() {
final stock = <String, int>{'apple': 3, 'pear': 0};
stock['plum'] = 5; // insert
stock['apple'] = 4; // replace
print(stock['apple']); // 4
print(stock['kiwi']); // null, not an error
print(stock.containsKey('pear')); // true
}Lookups return a nullable value
The type of stock['apple'] is int?, not int. A missing key yields null instead of throwing, so the compiler forces you to decide what a miss means. Three common choices:
- Supply a default with
??:final n = stock['kiwi'] ?? 0; - Test first and promote with a local variable:
final n = stock['kiwi']; if (n != null) { ... } - Assert presence with
!:stock['kiwi']!. This throws at run time if the key is absent. Use it only when you have just established the key exists.
Do not write if (stock['kiwi'] != null) print(stock['kiwi']! + 1);. Dart cannot promote a map lookup, because two calls could return different things. Store the result in a local variable and test that.
Missing key versus null value
If the value type is itself nullable, null becomes ambiguous.
void main() {
final prefs = <String, String?>{'theme': null};
print(prefs['theme']); // null, the key exists with a null value
print(prefs['lang']); // null, the key is absent
print(prefs.containsKey('theme')); // true
print(prefs.containsKey('lang')); // false
}When null is a legitimate value, use containsKey to tell the two cases apart.
Conditional updates
Three methods avoid the read-then-write pattern.
| Method | Behavior | Returns |
|---|---|---|
| `putIfAbsent(key, () => v)` | Calls the closure and stores the result only if the key is missing | The value now stored for the key |
| `update(key, (v) => ..., ifAbsent: () => ...)` | Replaces an existing value. Without `ifAbsent`, a missing key throws `ArgumentError`. | The new value |
| `updateAll((k, v) => ...)` | Recomputes every value | `void` |
The classic use is counting.
void main() {
final words = ['a', 'b', 'a', 'c', 'a', 'b'];
final counts = <String, int>{};
for (final w in words) {
counts.update(w, (n) => n + 1, ifAbsent: () => 1);
}
print(counts); // {a: 3, b: 2, c: 1}
final groups = <int, List<String>>{};
for (final w in ['kiwi', 'fig', 'plum', 'pear']) {
groups.putIfAbsent(w.length, () => []).add(w);
}
print(groups); // {4: [kiwi, plum, pear], 3: [fig]}
}The putIfAbsent form is the standard way to build a "map of lists". It returns the list stored under the key, whether it was just created or already there, so you can call add on the result directly.
Removing entries
remove(key) deletes the entry and returns the old value, or null if the key was absent. removeWhere deletes every entry that matches a test. clear empties the map.
void main() {
final stock = <String, int>{'apple': 3, 'pear': 0, 'plum': 5};
print(stock.remove('pear')); // 0
print(stock.remove('zzz')); // null
stock.removeWhere((key, value) => value > 4);
print(stock); // {apple: 3}
}Iterating
A map is not an Iterable, so you cannot write for (final x in map). Instead, it exposes three iterable views.
keysgives the keys.valuesgives the values.entriesgivesMapEntryobjects withkeyandvalue.
void main() {
final prices = {'apple': 1.5, 'pear': 2.0, 'fig': 3.25};
for (final entry in prices.entries) {
print('${entry.key} costs ${entry.value}');
}
prices.forEach((name, price) => print('$name: $price'));
final doubled = prices.map((k, v) => MapEntry(k, v * 2));
print(doubled); // {apple: 3.0, pear: 4.0, fig: 6.5}
final costly = Map.fromEntries(
prices.entries.where((e) => e.value > 1.8),
);
print(costly); // {pear: 2.0, fig: 3.25}
final names = prices.keys.toList()..sort();
print(names); // [apple, fig, pear]
}keys and values are live views, not copies. They reflect later changes to the map. Call .toList() when you need a snapshot. Because they are lazy iterables, where and map on them return lazy iterables too. To get a map back from a filtered result, wrap it in Map.fromEntries, or use a collection for inside a map literal.
Do not change the keys while iterating
Adding or removing keys during a loop over keys, values, or entries throws ConcurrentModificationError.
void main() {
final m = {'a': 1, 'b': 2};
try {
for (final k in m.keys) {
m.remove(k);
}
} on ConcurrentModificationError {
print('cannot add or remove keys while iterating');
}
print(m.length); // 1
}The first removal succeeds. The iterator then notices the change and throws on the next step. Two safe patterns exist: call removeWhere, or iterate over a copy such as m.keys.toList().
Keys: what makes a good one
A key is found through hashCode and ==. This has three consequences.
- Strings, numbers, and booleans work as keys because they compare by value.
- A
Listdoes not compare by value.[1, 2] == [1, 2]isfalse, so a list used as a key can never be found again through an equal-looking list. Use a string such as'1,2', a record, or a class with value equality instead. - Do not mutate an object in a way that changes its
hashCodeafter using it as a key. The map filed it under the old hash and will no longer find it.
A later chapter covers overriding == and hashCode for your own classes.
Order and null keys
A map literal and Map() give a LinkedHashMap, which iterates in insertion order. Replacing the value of an existing key keeps the key's original position. Removing a key and adding it again moves it to the end. If you need keys in sorted order, SplayTreeMap provides that, as a later chapter explains.
Dart's default map accepts null as a key when the key type is nullable, such as Map<String?, int>. That is rarely a good idea, because it makes every lookup harder to read.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `A value of type 'int?' can't be assigned to a variable of type 'int'` | Using a lookup result directly | Use `??`, a null check, or `!` after `containsKey` |
| `Null check operator used on a null value` | `map[key]!` with an absent key | Check `containsKey` or provide a default |
| `ArgumentError` from `update` | Key is missing and `ifAbsent` was not given | Add `ifAbsent` |
| `ConcurrentModificationError` | Adding or removing keys inside a loop over the map | Use `removeWhere` or iterate over a copy |
| `UnsupportedError` when writing | The map is a `const` or unmodifiable map | Create a growable copy with `Map.of(original)` |
| `{}` is not a set | Untyped `{}` is `Map<dynamic, dynamic>` | Write `<int>{}` for an empty set |
Exercise
Given final scores = <String, int>{'Ana': 90};, write one line that adds 5 to Ana's score, or sets a new player's score to 5 if the name is not yet present. Then explain why scores['Ben'] + 5 does not compile.
Show answer
Use scores.update('Ana', (s) => s + 5, ifAbsent: () => 5);. The expression scores['Ben'] + 5 does not compile because scores['Ben'] has type int?, and Dart does not allow + on a value that might be null. Use (scores['Ben'] ?? 0) + 5 instead.
Exercise
What does this program print, and why? final m = <String, String?>{'a': null}; print(m['a'] == m['b']); print(m.containsKey('a') == m.containsKey('b'));
Show answer
It prints true and then false. Both lookups return null, so they compare equal, even though only 'a' is a real key. containsKey distinguishes the two cases: true for 'a' and false for 'b'.