Skip to content
AgileLogics
6 min read

Maps

Prerequisites: Lists, Working with nullable values

A map stores key-value pairs: you look up a value by its key instead of by position.

Real-world analogy: a map is a contacts list — you find a phone number by the person's name, not by where it is in the list.

Creating and reading maps

void main() {
  final ages = {'Ada': 36, 'Linus': 28};   // Map<String, int>

  print(ages['Ada']);
  print(ages['Grace']);
  print(ages['Grace'] ?? 0);
  print(ages.containsKey('Linus'));
  print(ages.keys);
  print(ages.values);
  print(ages.length);
  print(ages);
}
36
null
0
true
(Ada, Linus)
(36, 28)
2
{Ada: 36, Linus: 28}
  • Looking up a missing key returns null, so lookups are nullable.
  • keys and values are iterables (printed in parentheses); call .toList() if you need a list.
  • Maps keep the order in which keys were added.

Changing a map

void main() {
  final stock = {'apples': 10, 'pears': 4};

  stock['plums'] = 7;
  stock['apples'] = 12;
  stock.remove('pears');
  stock.update('apples', (n) => n + 1);
  stock.putIfAbsent('kiwis', () => 0);

  for (final MapEntry(:key, :value) in stock.entries) {
    print('$key: $value');
  }
}
apples: 13
plums: 7
kiwis: 0

MapEntry(:key, :value) is a pattern that unpacks each entry into key and value variables.

Common mistakes

  • Using a looked-up value as non-null: ages['Ada'] + 1 doesn't compile, because the lookup is an int?. Use ?? 0, or ! only when you're certain the key exists.

Practice

Count how many times each word appears in ['red', 'blue', 'red', 'green', 'red'] and print the map.

Show solution
void main() {
  final words = ['red', 'blue', 'red', 'green', 'red'];
  final counts = <String, int>{};

  for (final word in words) {
    counts.update(word, (n) => n + 1, ifAbsent: () => 1);
  }

  print(counts);
}
{red: 3, blue: 1, green: 1}