Dart Maps
A map is a collection that stores values under keys. A key finds its value again later.
A map of scores
The map literal sits on one line with a key and a value in each pair. Print shows both pairs in the order they were written.
void main() {
var scores = {'Ana': 90, 'Bo': 75};
print(scores);
}Reading a value by key
Each print reads one value through its key. Ana gives 90 and Bo gives 75.
void main() {
var scores = {'Ana': 90, 'Bo': 75};
print(scores['Ana']);
print(scores['Bo']);
}A missing key with a fallback
The map holds no Cy key, so the first read gives null. The ?? fallback swaps that null for 0 in the second read.
void main() {
var scores = {'Ana': 90, 'Bo': 75};
print(scores['Cy']);
print(scores['Cy'] ?? 0);
}Adding and changing entries
The Cy line adds a new entry at the end of the map. The Bo line changes the value that Bo already held.
void main() {
var scores = {'Ana': 90, 'Bo': 75};
scores['Cy'] = 60;
scores['Bo'] = 80;
print(scores);
}Example
void main() {
var prices = {'pen': 2, 'book': 5};
print(prices['pen']);
prices['ruler'] = 3;
print(prices);
print(prices.length);
}Key points
- A map stores pairs of a key and a value.
- Each value in a map sits behind its own key.
- Use a key inside square brackets to read its value.
- A missing key reads as null.
- Use = with a key to add a new entry or change an old one.
- The length of a map counts its entries.
In this example, prices starts with a pen at 2 and a book at 5. The first print reads the pen value through its key and shows 2. The next line adds a ruler at 3. The second print shows all three entries in the order they were added. The last print shows the length 3.
Note
Print shows a map with curly braces and a colon after each key.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What does a missing key read as in a map?