Explain it simply
Explain it simply
A map works like a dictionary or the contact list on your phone. You do not flip to page 37; you look up a name (the key) and get the phone number (the value) tied to it. Each key owns exactly one value, and writing the same key again replaces the old value.
A list finds things by box number, but a map finds them by a key you choose yourself, such as a String or an int. That makes it the natural fit for data you want to ask for by name: user profiles, inventories and settings.
Problem → Why → Solution
The problem: two parallel lists drift apart
Suppose you keep player names in one list and their points in another, matched by position. To find Kyaw's points you search the names, then use the index on the points list. The danger is that editing one list and not the other makes the data drift apart without any error. In the code below, after Aye is removed, what looks like Kyaw's score is really Aye's 120.
void main() {
List<String> names = ['Aye', 'Kyaw', 'Thida'];
List<int> points = [120, 85, 97];
// Find Kyaw's points: search the names, then reuse the index.
int index = names.indexOf('Kyaw');
print(points[index]); // 85
// One list is edited and the other is forgotten.
names.removeAt(0);
print(points[names.indexOf('Kyaw')]); // 120: Aye's points, silently wrong
}What a map prevents
In a map the key and value are stored together, so removing one removes the other and this kind of drift cannot happen. Lookup is also direct, points['Kyaw'], with no need to scan a whole list for an index, and it is fast in practice. You do have to think about what happens when a key is missing and what type the values have, which is what this lesson explains.
Core concept: map types, null results and ordering
A map literal is written { key: value } and its type as Map<String, int>. Dart infers Map<String, int> from {'a': 1, 'b': 2}, and mixing value types, as in {'name': 'Sai', 'points': 120}, gives Map<String, Object>. var empty = {}; becomes Map<dynamic, dynamic>, so write <String, int>{}. JSON-like data often uses Map<String, dynamic>, but dynamic switches off checking of the value type: int p = user['points'] compiles, and if the value turns out to be a String it fails at run time with "type 'String' is not a subtype of type 'int'".
The result of map[key] is not the value type but V?: a missing key returns null instead of throwing. So with Map<String, int> stock, int n = stock['tea']; fails with "A value of type 'int?' can't be assigned to a variable of type 'int'." The fixes are a default with stock['tea'] ?? 0, an earlier containsKey check, or ! when you are certain, and ! crashes with "Null check operator used on a null value" if the key is missing. When the value type is itself nullable (int?), use containsKey to tell a missing key from a stored null.
For writing, map[key] = value both adds and replaces. remove(key) returns the removed value, or null when the key was absent. putIfAbsent(key, () => value) calls the function and stores the result only when the key is missing, and returns the value now in the map. update(key, (v) => newValue) changes an existing value; if the key is missing and no ifAbsent: () => value is supplied it throws an ArgumentError ("Invalid argument (key): Key not in map."). addAll, removeWhere and clear are available too.
To iterate you have keys, values and entries; entries yields MapEntry objects with entry.key and entry.value, and forEach((k, v) => ...) also works. The ordinary Map created by a literal is a LinkedHashMap that remembers insertion order, so keys come back in the order they were first added; updating an existing key keeps its position, while removing and re-adding it moves it to the end. HashMap from dart:collection makes no ordering promise, and SplayTreeMap keeps keys sorted. Adding or removing keys while iterating raises a ConcurrentModificationError.
Keys are compared with == and hashCode, so String and int keys are safe, while using a mutable list as a key is dangerous. Two maps with the same contents are still not ==, because maps, like lists, compare by identity. Map.unmodifiable(source) and const {} cannot be changed; trying gives "Unsupported operation: Cannot modify unmodifiable map". You can build new maps with {...other, 'c': 3}, {for (final e in ...) e.key: e.value}, or map.map((k, v) => MapEntry(k, v * 2)).
- Each key owns exactly one value
- map[key] gives V?: null if missing
- Insertion order is remembered
- Same key again replaces the value
Each time you read a map, ask what should happen if the key is missing; Dart answers with null, so you must handle it yourself.
General pattern
Map<KeyType, ValueType> name = {key1: value1, key2: value2};
var empty = <KeyType, ValueType>{};
name[key] = value; // add or replace
ValueType? found = name[key]; // null when the key is missing
name.putIfAbsent(key, () => value); // add only if the key is missing
name.update(key, (v) => newValue, ifAbsent: () => value);
for (final entry in name.entries) { /* entry.key, entry.value */ }A map is declared with both a key type and a value type. Remember that reading gives ValueType?. putIfAbsent and update check for presence and add or change in a single step, and entries hands you both key and value at once.
Example: a user profile and a stock list
In this example the first Map<String, dynamic> stands for a user profile with mixed value types (String, int, bool). You read it, change it, and see that reading a missing key gives null. Then a Map<String, int> stock, whose values are all ints, is changed with putIfAbsent and update and printed through entries.
void main() {
Map<String, dynamic> user = {
'name': 'Sai',
'role': 'Developer',
'points': 120,
'isActive': true,
};
print(user['name']);
print(user['points']);
user['points'] = 150;
print('Updated points: ${user['points']}');
// a missing key gives null, not an error
print(user['email']);
// a typed map: every value is an int
Map<String, int> stock = {'tea': 5, 'rice': 2};
stock.putIfAbsent('coffee', () => 9);
stock.update('tea', (count) => count + 1);
for (final entry in stock.entries) {
print('${entry.key}: ${entry.value}');
}
}Code breakdown
- Line 2
Map<String, dynamic> user = {Every key is a String and values are dynamic, so Strings, ints and bools can be mixed. Maps like this are common for data that came from JSON.
- Line 12
user['points'] = 150;The 'points' key already exists, so its value 120 is replaced by 150. With a new key the same syntax would add an entry; the syntax is identical for both.
- Line 16
print(user['email']);There is no 'email' key, so no error is thrown; the lookup returns null and print shows null.
- Line 19
Map<String, int> stock = {'tea': 5, 'rice': 2};A typed map whose values are all ints. Here stock['tea'] has type int?, and trying to store a string under 'tea' is a compile error.
- Line 20
stock.putIfAbsent('coffee', () => 9);The 'coffee' key is not there yet, so the function runs and 9 is stored. If the key already existed, the function would not run at all and the old value would stay.
- Line 21
stock.update('tea', (count) => count + 1);The existing value 5 for 'tea' is passed to the function and the result 6 is stored back. If 'tea' were missing, there is no ifAbsent, so an ArgumentError would be thrown.
- Line 23
for (final entry in stock.entries) {entries gives each key and value together as a MapEntry. The output follows insertion order, tea, rice, coffee; updating tea did not move it.
Sai
120
Updated points: 150
null
tea: 6
rice: 2
coffee: 9Reading safely: null, containsKey and typed maps
In the code below, int n = stock['tea']; sits in a comment because it is a compile error. You can see three ways to read safely: a default with ?? 0, an earlier containsKey check, and storing the result in an int? variable and using it only when it is not null (type promotion applies inside that block). The last lines use entries.reduce to find the entry with the highest value.
void main() {
Map<String, int> stock = {'tea': 5, 'rice': 2};
// int n = stock['tea']; // compile error: the result is int?
int tea = stock['tea'] ?? 0;
int coffee = stock['coffee'] ?? 0;
print('$tea $coffee');
if (stock.containsKey('rice')) {
print('rice is listed');
}
int? maybe = stock['milk'];
if (maybe != null) {
print(maybe + 1); // promoted to int inside this block
} else {
print('no milk');
}
var scores = {'aye': 80, 'kyaw': 65};
var best = scores.entries.reduce((a, b) => a.value >= b.value ? a : b);
print(best.key);
}Counting, grouping and ordering
| Kind of map | How you get it | Key order |
|---|---|---|
| Default (LinkedHashMap) | { } literal, Map.of(x) | Insertion order |
| HashMap | dart:collection | No promise |
| SplayTreeMap | dart:collection | Sorted by key |
Counting and grouping are the two most common map patterns. update combined with ifAbsent bumps the count for each word. putIfAbsent(key, () => []) creates an empty list when the key is missing, and you can call .add on the result immediately. map.map(...) returns a new map, and SplayTreeMap.from sorts the keys.
import 'dart:collection';
void main() {
var words = ['to', 'be', 'or', 'not', 'to', 'be'];
var counts = <String, int>{};
for (final w in words) {
counts.update(w, (n) => n + 1, ifAbsent: () => 1);
}
print(counts);
var byLength = <int, List<String>>{};
for (final w in ['fig', 'pear', 'kiwi', 'plum', 'yam']) {
byLength.putIfAbsent(w.length, () => []).add(w);
}
print(byLength);
var doubled = counts.map((word, n) => MapEntry(word, n * 2));
print(doubled);
var sorted = SplayTreeMap<String, int>.from(counts);
print(sorted);
}Do not change a map while iterating it
Writing for (final k in map.keys) { map.remove(k); } raises a ConcurrentModificationError. If you want to delete by a condition, use map.removeWhere((k, v) => v > 20), or copy the keys first (map.keys.toList()) and loop over that list.
In real projects
Where this shows up in real projects
Reading server JSON with jsonDecode gives you Map<String, dynamic> values, and the usual practice is to convert such a map into a typed class such as User (covered in later lessons) at the boundary and work with typed data inside the app. In Flutter, a route table like routes: {'/home': (context) => HomePage()} is a map, and so are settings, translation strings and HTTP headers.
For caching, cache.putIfAbsent(id, () => expensiveLoad(id)) makes sure the same id is not recomputed when asked again. In analytics, each event name is counted with counts.update(name, (n) => n + 1, ifAbsent: () => 1), and grouping items by category uses putIfAbsent(category, () => []).add(item). Tests also build request bodies as maps and compare them with the response that comes back.
Common mistakes
Common mistakes
1. Assuming map[key] is never null
With Map<String, int> stock, int n = stock['tea']; reports "A value of type 'int?' can't be assigned to a variable of type 'int'." Adding ! to silence it makes stock['coffee']! + 1 stop with "Null check operator used on a null value" when the key is missing. Handle the case with ?? 0 or containsKey.
2. Calling update on a missing key without ifAbsent
Running Map<String, int> m = {'a': 1}; m.update('b', (v) => v + 1); throws an ArgumentError whose message starts with "Invalid argument (key): Key not in map." and also names the missing key 'b'. In counting code pair update with ifAbsent: () => 1, or write m['b'] = (m['b'] ?? 0) + 1.
3. Hiding type mistakes behind dynamic
Reading int p = user['points']; from a Map<String, dynamic> compiles, but breaks at run time if the value is a String. With var user = {'name': 'Sai', 'points': 120}; the map is Map<String, Object>, user['points'] has type Object?, and you get the compile error "A value of type 'Object?' can't be assigned to a variable of type 'int'." Resolve it with an is check or a typed class.
4. Removing keys while iterating
for (final k in order.keys) { order.remove(k); } throws a ConcurrentModificationError. Removing the first element changes the map underneath the loop, which can no longer continue safely. Use removeWhere instead.
Best practices
Best practices
- Prefer precise types such as Map<String, int>; keep Map<String, dynamic> at boundaries like JSON and convert it to classes inside the app.
- Choose map[key] ?? default over map[key]!; when a missing key is a normal case, this form cannot crash.
- When you need both key and value, loop over entries instead of looping over keys and looking each one up.
- Use update and putIfAbsent for counting and grouping; they are shorter and clearer than an if that checks for presence.
Mini challenge
Mini challenge: word counts and restocking
Write three map helpers: count the words in a text, find the most frequent word, and produce a new map when a delivery arrives without changing the original stock.
- Map<String, int> countWords(String text): lowercase the text, split on spaces and count with update and ifAbsent
- String mostCommon(Map<String, int> counts): return the key with the highest count, or 'none' for an empty map
- Map<String, int> restock(Map<String, int> stock, Map<String, int> delivery): copy stock, add every delivery amount and return the new map without changing stock
- In main, count 'Tea tea rice Tea rice coffee' and print the most common word, then print the restock result and the original stock
Map<String, int> countWords(String text) {
// TODO: lowercase, split on spaces, count with update and ifAbsent
}
String mostCommon(Map<String, int> counts) {
// TODO: find the key with the highest count; 'none' when the map is empty
}
Map<String, int> restock(Map<String, int> stock, Map<String, int> delivery) {
// TODO: copy stock first, then add each delivery amount to the copy
}
void main() {
// TODO: count 'Tea tea rice Tea rice coffee', print counts and the top word
// TODO: restock {'tea': 2, 'rice': 1} with {'rice': 4, 'coffee': 3}
// TODO: print the new map and then the original stock
}Expected: Expected output: {tea: 3, rice: 2, coffee: 1} tea {tea: 2, rice: 5, coffee: 3} {tea: 2, rice: 1}
Show hint
In restock, copy with Map<String, int>.of(stock) before changing anything, and inside delivery.forEach((item, qty) { ... }) pair update with ifAbsent. For mostCommon, counts.entries.reduce compares two entries and keeps one; take .key from the result.
Show solution
Map<String, int> countWords(String text) {
final counts = <String, int>{};
for (final word in text.toLowerCase().split(' ')) {
counts.update(word, (n) => n + 1, ifAbsent: () => 1);
}
return counts;
}
String mostCommon(Map<String, int> counts) {
if (counts.isEmpty) {
return 'none';
}
return counts.entries.reduce((a, b) => b.value > a.value ? b : a).key;
}
Map<String, int> restock(Map<String, int> stock, Map<String, int> delivery) {
final result = Map<String, int>.of(stock);
delivery.forEach((item, qty) {
result.update(item, (current) => current + qty, ifAbsent: () => qty);
});
return result;
}
void main() {
final counts = countWords('Tea tea rice Tea rice coffee');
print(counts);
print(mostCommon(counts));
final stock = {'tea': 2, 'rice': 1};
print(restock(stock, {'rice': 4, 'coffee': 3}));
print(stock);
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A map pairs each key with one value, and writing an existing key replaces its value.
- map[key] returns V?, which is null for a missing key, so handle it with ?? default, containsKey or a null check.
- putIfAbsent adds only when missing, update changes only what exists (an error for a missing key without ifAbsent), and entries gives key and value together.
- The default map remembers insertion order, and Map<String, dynamic> relaxes type checking, so keep it at boundaries.
Dart language overview — Dart