Map
- Dart course
- Beginner
- Lesson 61/116
- 5 min
Learn key-value collections with Map.
The Map collection
A Map is a collection that holds key-value pairs. Each key appears at most once; if you write the same key twice, the last value wins.
The Map literal is {key: value}. For example var ages = <String, int>{'Ayşe': 28, 'Mert': 31};. Here the keys are strings and the values are integers.
You can also give the Map the explicit type Map<K, V>. A bare {} works for an empty Map, but <K, V>{} reads more clearly.
Creating a Map
You can build a Map with a literal or a constructor. Literal: var codes = <String, int>{'apple': 1, 'pear': 2};. This yields a Map with two pairs.
Starting empty and filling later is also common: var codes = <String, int>{};. The type parameters <String, int> fix the key and value types.
The length property returns the number of pairs; keys and values return only the keys or the values in insertion order.
Practice Three ages
Create a Map<String, int> with three people: name as key, age as value. Then print the Map with print.
Starter code
void main() {
// Define the Map with three pairs
// print
}Sample solution
void main() {
var ages = <String, int>{'Ayşe': 28, 'Mert': 31, 'Deniz': 24};
print(ages);
}Expected output
{Ayşe: 28, Mert: 31, Deniz: 24}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the Map parts
| Term | Meaning |
|---|---|
key |
Name used for access |
value |
Data stored under the key |
<String,int> |
String keys, int values |
{a: 1} |
One-pair Map literal |
2 What if the same key is written twice?
- Throws an error
- Last value wins Correct answer
- First value wins
- Both are kept
Explanation: a Map key is unique, the last value overwrites the previous.
3 Define a Map
void main() {
var ages = ____;
print(ages);
}
void main() {
var ages = <String, int>{'Ayşe': 28};
print(ages);
}
Explanation: <String, int> sets the key and value types in order.