Sub topic 3
Maps: Looking Up Values by Key
Prerequisites and the map model
This chapter assumes you know basic Dart syntax, variables, functions, control flow, generics such as Map<String, int>, and nullable types such as int?.
A Map<K, V> stores pairs of keys and values. K is the key type, and V is the value type. Each key identifies at most one value. Use a map when you need to find data by a meaningful identifier instead of by a numeric position.
For example, a product code can identify a product price:
| Key | Value |
|---|---|
| `"apple"` | 3 |
| `"pear"` | 0 |
Creating and changing a map
A map literal is the shortest way to create a map. Dart infers its key and value types from the entries. You can also write the types explicitly when that makes the contract clearer.
void main() {
final stock = <String, int>{
'apple': 3,
'pear': 0,
};
stock['plum'] = 5; // Add a new key and value.
stock['apple'] = 4; // Replace the value for an existing key.
stock.update('pear', (quantity) => quantity + 2);
stock.putIfAbsent('fig', () => 2);
print(stock);
}Assigning to map[key] adds the key if it is absent and replaces its value if it already exists. update calculates a replacement from the old value. putIfAbsent calculates and inserts a value only when the key is missing.
Looking up values safely
A lookup uses bracket notation:
final quantity = stock['apple'];The result has type int?, not int. A key might not exist, so Dart requires you to handle the missing case.
Use ?? to provide a fallback:
final kiwiQuantity = stock['kiwi'] ?? 0;
print(kiwiQuantity); // 0Use containsKey when you need to know whether the key exists:
if (stock.containsKey('apple')) {
print('Apple stock: ${stock['apple']}');
}containsKey matters when a map is allowed to store null. In that case, a lookup that returns null could mean either “the key is absent” or “the key exists with a null value.”
Removing entries and iterating
remove deletes an entry and returns its old value, or null when no entry matched. removeWhere deletes every entry that satisfies a condition.
The entries property provides key-value pairs for iteration:
void main() {
final stock = <String, int>{
'apple': 3,
'pear': 0,
};
final removed = stock.remove('pear');
print(removed); // 0
stock['plum'] = 5;
for (final entry in stock.entries) {
print('${entry.key}: ${entry.value}');
}
}Use for-in when the loop needs both the key and value. Use keys or values when you need only one side.
A lookup decision
Exercise
How do you read a map value while using 0 when the key is missing?
Show answer
Use final value = map[key] ?? 0;. The lookup is nullable, and ?? supplies 0 when it is null.