What is a Map?
A Map stores data as key-value pairs. Each key must be unique, but values can repeat. Maps are ideal for looking up data by a meaningful label (like a dictionary or JSON object).
Creating Maps
// String keys, int values
Map<String, int> scores = {
'Alice': 95,
'Bob': 87,
'Carol': 92,
};
// Dynamic values
Map<String, dynamic> user = {
'name': 'John',
'age': 30,
'isAdmin': false,
};
// Empty map
var config = <String, String>{};
Accessing Values
print(scores['Alice']); // 95
print(scores['Unknown']); // null (key not found)
// Safe access with default
int bobScore = scores['Bob'] ?? 0;
print(bobScore); // 87
// Check key existence
print(scores.containsKey('Carol')); // true
print(scores.containsValue(100)); // false
Common Methods
| Method/Property | Description |
keys | All keys as an Iterable |
values | All values as an Iterable |
entries | All key-value pairs |
length | Number of entries |
remove(key) | Remove an entry |
putIfAbsent(k,f) | Add only if key missing |
update(k,f) | Update value for key |
Example
void main() {
Map<String, int> inventory = {
'apples': 50, 'bananas': 30, 'oranges': 20
};
// Add / update
inventory['grapes'] = 15;
inventory['apples'] = 45;
// Iterate
inventory.forEach((item, qty) {
print('$item: $qty units');
});
// Keys and values
print('Items: $${inventory.keys.toList()}');
print('Total: $${inventory.values.reduce((a, b) => a + b)}');
// Remove
inventory.remove('bananas');
print('After removal: $${inventory.length} items');
}
Output:apples: 45 units
bananas: 30 units
oranges: 20 units
grapes: 15 units
Items: [apples, bananas, oranges, grapes]
Total: 110
After removal: 3 items
💪 Exercise
- Create a phone book Map with 5 contacts. Add, update, and remove one.
- Count the frequency of each character in a string using a Map.
- Invert a Map (swap keys and values).
🧠 Quiz
1. What does accessing a missing key in a Map return?
- A) Error
- B) 0
- C) null ✅
- D) empty string
2. Which property returns all keys of a Map?
- A) map.keySet()
- B) map.keys ✅
- C) map.getKeys()
- D) map.allKeys
Summary
Maps store key-value pairs with unique keys. Access values with map[key] (returns null if missing). Use forEach() to iterate entries. Key properties: keys, values, entries, length. Use ?? for null-safe access with defaults.