Map operations
- Dart course
- Beginner
- Lesson 62/116
- 5 min
Learn Map management with [] and .putIfAbsent.
Map operations
Read a value from a Map with square brackets: ages['Ayşe'] returns the value for 'Ayşe', or null if it is missing. Adding a pair uses the same syntax: ages['Cem'] = 26;.
putIfAbsent places a value only when the key is absent: ages.putIfAbsent('Deniz', () => 30);. If the key exists it does nothing; otherwise it calls the given function and stores the result.
Use remove to delete and entries to see all pairs. length reports the count. Because the [] operator returns null for a missing key, null safety matters here; the next group dives into that.
putIfAbsent vs update
putIfAbsent only sets a value when the key is absent; if present, it leaves it untouched. update changes the existing value; if the key is missing it may throw or compute a default.
For example ages.putIfAbsent('Cem', () => 25); sets 25 when 'Cem' is missing. ages.update('Ayşe', (v) => v + 1); increments Ayşe's age by one.
Reach for putIfAbsent on first insert and update when you need to modify. Pick the one that matches your task.
Practice Phone book
Create an empty Map<String, String>. Use putIfAbsent to add two people: name as key, phone as value. Then print the phone book with print.
Starter code
void main() {
var phones = <String, String>{};
// putIfAbsent two people
// print
}Sample solution
void main() {
var phones = <String, String>{};
phones.putIfAbsent('Ayşe', () => '555-1000');
phones.putIfAbsent('Mert', () => '555-2000');
print(phones);
}Expected output
{Ayşe: 555-1000, Mert: 555-2000}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does putIfAbsent set a value?
- Always
- When the key exists
- Never
- When the key is missing Correct answer
Explanation: putIfAbsent only sets a value when the key is absent.
2 Read a value
void main() {
var ages = <String, int>{'Ayşe': 28};
print(ages____);
}
void main() {
var ages = <String, int>{'Ayşe': 28};
print(ages['Ayşe']);
}
Explanation: square brackets fetch the value for the key.
3 Match the operations
| Term | Meaning |
|---|---|
[] |
Read or write a value |
putIfAbsent |
Only set if absent |
update |
Modify existing |
remove |
Delete the key |