On this page12 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Creating a Map
  4. 2. Reading Values
  5. 3. Adding, Changing, Removing
  6. 4. Looking Inside
  7. 5. putIfAbsent and update
  8. Code Examples
  9. Common Beginner Mistakes
  10. Practice Questions
  11. Practice Answers
  12. Key Takeaways

Lecture 014: Maps

Day5: Lists & Maps
Lecture014 of 057
Estimated video length14 min
TargetDart 3.12
LevelBeginner

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, containsKey and containsValue
  • Use putIfAbsent and update

1. Creating a Map

Curly braces, with key: value pairs:

dart
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.

ListMap
['Ali', 'Sara']{'Ali': 20, 'Sara': 19}
find by position: list[0]find by key: map['Ali']

2. Reading Values

dart
print(student['name']);  // Ayesha
print(ages['Sara']);     // 19
print(ages['Bilal']);    // null: no such key
print(student.length);   // 3

A missing key gives null, so the result of map[key] is nullable (int?). Give a default with ?? (Lecture 010):

dart
print(ages['Zara'] ?? 0);   // 0

3. Adding, Changing, Removing

The same map[key] = value adds a new pair or replaces an existing one:

dart
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

dart
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);                    // true

keys and values are iterables; add .toList() for a list.

5. putIfAbsent and update

dart
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

dart
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

code
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: 0

stock['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

dart
var ages = {'Ali': 20};
int a = ages['Ali'];
code
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

dart
var ages = {'Ali': 20};
ages[5] = 30;
code
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

  1. Create a map capitals with Pakistan → Islamabad and Turkey → Ankara.
  2. What does capitals['Japan'] give?
  3. Write a line that adds Japan → Tokyo.
  4. How do you check whether the key 'Turkey' exists?
  5. What is the type of ages['Ali'] when ages is a Map<String, int>?
  6. What does {'x': 1}.putIfAbsent('x', () => 5) leave the value of 'x' as?

Practice Answers

  1. var capitals = {'Pakistan': 'Islamabad', 'Turkey': 'Ankara'};
  2. null
  3. capitals['Japan'] = 'Tokyo';
  4. capitals.containsKey('Turkey')
  5. int?
  6. 1. The key already existed, so nothing changed.

Key Takeaways

  • A map stores key: value pairs; keys are unique.
  • map[key] reads (nullable), map[key] = value adds or changes, remove(key) deletes.
  • Use ?? for a default when a key may be missing.
  • keys, values, containsKey, containsValue look inside.
  • putIfAbsent adds only if missing; update changes using the old value.