On this page12 sections
Lecture 014: Maps
| Day | 5: Lists & Maps |
| Lecture | 014 of 057 |
| Estimated video length | 14 min |
| Target | Dart 3.12 |
| Level | Beginner |
A dictionary pairs each word with its meaning; a phone book pairs each name with a number. A map stores pairs like that: you look a value up by its key instead of by a numbered position.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 010 (null safety, ??) and 011 (lists).
Learning Objectives
- Create a map of key-value pairs
- Read, add, change and remove entries
- Know why reading a map gives a nullable value
- Use
keys,values,containsKeyandcontainsValue - Use
putIfAbsentandupdate
1. Creating a Map
Curly braces, with key: value pairs:
var student = {
'name': 'Ayesha',
'city': 'Lahore',
'grade': 'A',
};
Map<String, int> ages = {'Ali': 20, 'Sara': 19};
var empty = <String, double>{};
print(student); // {name: Ayesha, city: Lahore, grade: A}Map<String, int> means "keys are Strings, values are ints". Keys must be unique; values
can repeat.
| List | Map |
|---|---|
['Ali', 'Sara'] | {'Ali': 20, 'Sara': 19} |
find by position: list[0] | find by key: map['Ali'] |
2. Reading Values
print(student['name']); // Ayesha
print(ages['Sara']); // 19
print(ages['Bilal']); // null: no such key
print(student.length); // 3A missing key gives null, so the result of map[key] is nullable (int?). Give a
default with ?? (Lecture 010):
print(ages['Zara'] ?? 0); // 03. Adding, Changing, Removing
The same map[key] = value adds a new pair or replaces an existing one:
student['city'] = 'Karachi'; // change
student['phone'] = '0300-1234567'; // add
print(student);
// {name: Ayesha, city: Karachi, grade: A, phone: 0300-1234567}
student.remove('grade');
print(student);
// {name: Ayesha, city: Karachi, phone: 0300-1234567}4. Looking Inside
print(student.keys); // (name, city, phone)
print(student.values); // (Ayesha, Karachi, 0300-1234567)
print(student.containsKey('name')); // true
print(student.containsValue('Lahore')); // false (it's Karachi now)
print(empty.isEmpty); // truekeys and values are iterables; add .toList() for a list.
5. putIfAbsent and update
ages.putIfAbsent('Bilal', () => 22); // added: Bilal wasn't there
ages.putIfAbsent('Ali', () => 99); // ignored: Ali already exists
print(ages); // {Ali: 20, Sara: 19, Bilal: 22}
ages.update('Ali', (age) => age + 1); // change based on the old value
print(ages); // {Ali: 21, Sara: 19, Bilal: 22}Keys don't have to be strings: var squares = {1: 1, 2: 4, 3: 9}; uses int keys, and
squares[3] is 9.
Going through every pair in a map uses a loop, which you'll learn on Day 8.
Code Examples
Example 1: Shop Stock
void main() {
var stock = {'Pen': 50, 'Notebook': 20, 'Bag': 5};
var prices = {'Pen': 40, 'Notebook': 150, 'Bag': 1800};
print('Items: ${stock.keys.toList()}');
print('Notebooks left: ${stock['Notebook']}');
stock['Pen'] = stock['Pen']! - 3;
stock.update('Bag', (n) => n - 1);
stock['Ruler'] = 30;
prices['Ruler'] = 25;
print('Stock now: $stock');
print('Bag price: Rs ${prices['Bag']}');
print('Do we sell glue? ${stock.containsKey('Glue')}');
print('Glue in stock: ${stock['Glue'] ?? 0}');
}Output
Items: [Pen, Notebook, Bag]
Notebooks left: 20
Stock now: {Pen: 47, Notebook: 20, Bag: 4, Ruler: 30}
Bag price: Rs 1800
Do we sell glue? false
Glue in stock: 0stock['Pen']! uses ! because we know the pen key exists (Lecture 010). update is the
safer way to do the same thing.
Common Beginner Mistakes
1. Treating map[key] as non-nullable
var ages = {'Ali': 20};
int a = ages['Ali'];Error: A value of type 'int?' can't be assigned to a variable of type 'int'.The key might be missing. Use ages['Ali'] ?? 0, or check containsKey first.
2. A key of the wrong type
var ages = {'Ali': 20};
ages[5] = 30;Error: A value of type 'int' can't be assigned to a variable of type 'String'.This map's keys are Strings.
3. Repeating a key: {'a': 1, 'a': 2} keeps only the last one, {a: 2}. Each key appears
once.
4. Using an index: student[0] looks for a key called 0, not "the first entry". Maps are
read by key.
Practice Questions
- Create a map
capitalswith Pakistan → Islamabad and Turkey → Ankara. - What does
capitals['Japan']give? - Write a line that adds Japan → Tokyo.
- How do you check whether the key
'Turkey'exists? - What is the type of
ages['Ali']whenagesis aMap<String, int>? - What does
{'x': 1}.putIfAbsent('x', () => 5)leave the value of'x'as?
Practice Answers
var capitals = {'Pakistan': 'Islamabad', 'Turkey': 'Ankara'};nullcapitals['Japan'] = 'Tokyo';capitals.containsKey('Turkey')int?1. The key already existed, so nothing changed.
Key Takeaways
- A map stores
key: valuepairs; keys are unique. map[key]reads (nullable),map[key] = valueadds or changes,remove(key)deletes.- Use
??for a default when a key may be missing. keys,values,containsKey,containsValuelook inside.putIfAbsentadds only if missing;updatechanges using the old value.