Back to quest
Dart Basics & Data TypesLevel 11 / 32

Maps: Key-Value Pairs

Mastering dictionaries and data lookup in Dart

A Map in Dart is an object that associates keys with values. It is very similar to a real-world dictionary (where a word is the "key" and the definition is the "value") or a JSON object. Keys must be unique, but values can be duplicated.

1. Creating Maps

Maps can be declared using literal syntax with curly braces {} or by explicitly defining the types for both the Key and the Value.

Declaration Syntax

example.dart
1// Type Inference (Map<String, String>)
2var capitals = {
3 'USA': 'Washington D.C.',
4 'France': 'Paris',
5 'Japan': 'Tokyo'
6};
7 
8// Explicit Typing (Map<String, int>)
9Map<String, int> scores = {
10 'Alice': 95,
11 'Bob': 88,
12 'Charlie': 92
13};
14 
15// Empty Map
16var emptyMap = {}; // Dart infers this as Map<dynamic, dynamic>
17Map<String, dynamic> userProfile = {};

HintThe structure is always key: value. While keys are usually Strings, they can be numbers or other objects.

2. Accessing and Modifying Data

You access values using the subscript operator [] with the key. You can also add new entries or update existing ones using the same operator.

Reading and Writing

example.dart
1var inventory = {'Apples': 5, 'Oranges': 10};
2 
3// Reading a value
4print(inventory['Apples']); // Output: 5
5 
6// Adding a new item
7inventory['Bananas'] = 12;
8 
9// Updating an existing item
10inventory['Apples'] = 3; // Value changes from 5 to 3
11 
12print(inventory); // {Apples: 3, Oranges: 10, Bananas: 12}

HintNote: If you assign a value to a key that already exists, it updates the value. If the key does not exist, it adds a new entry.

3. Null Safety in Maps

A critical concept in Dart Maps is that accessing a key returns a "nullable" type. If the key is missing, Dart returns null rather than crashing.

Handling Missing Keys

example.dart
1var scores = {'Alice': 100};
2 
3print(scores['Bob']); // Output: null
4 
5// Handling the null safely
6int? bobScore = scores['Bob']; // Must be nullable int?
7 
8// Using the '!' operator if you are SURE the key exists (Risky)
9// int score = scores['Alice']!;
10 
11// Best practice: Check if key exists first
12if (scores.containsKey('Bob')) {
13 print('Bob score is ${scores['Bob']}');
14} else {
15 print('Bob did not play.');
16}

HintLooking up a key is one of the most common sources of null values in Dart programming. Always handle the possibility that a key might be missing.

4. Map Properties and Methods

Dart Maps include useful properties to iterate over data or check the map's status.

Useful Methods

example.dart
1var user = {
2 'name': 'Houssam',
3 'role': 'Admin',
4 'active': true
5};
6 
7print(user.length); // 3
8print(user.keys); // (name, role, active)
9print(user.values); // (Houssam, Admin, true)
10print(user.isEmpty); // false
11 
12// Removing an item
13user.remove('role');
14print(user); // {name: Houssam, active: true}

HintUsing .keys or .values returns an Iterable, which you can loop over easily.

Loot collected

Key takeaways
  • Maps store data in key: value pairs.
  • Keys must be unique; values can be duplicates.
  • Accessing a value: map[key]. If the key doesn't exist, it returns null.
  • Use .containsKey(key) to check for existence before accessing data.
  • The literal {} creates a Map, not a Set.

Side quests

Practice exercises

1

Exercise 1: Phonebook

Create a Map called phonebook storing two names (Strings) and phone numbers (Integers).

Reveal solution
solution.dart
1Map<String, int> phonebook = {'John': 123456, 'Jane': 987654};
2

Exercise 2: Updating Inventory

Given var stock = {"pens": 5};, write code to add 10 "pencils" and update "pens" to 3.

Reveal solution
solution.dart
1stock['pencils'] = 10; stock['pens'] = 3;
3

Exercise 3: Safe Lookup

Write code that prints the value for key "pizza" from a map menu, but prints "Not found" if it is missing.

Reveal solution
solution.dart
1var price = menu['pizza'];
2if (price != null) print(price); else print('Not found');
Party chat

Comments