Dart Map Iteration
A map can be walked entry by entry. Each entry hands over its key and its value together.
Loop over entries
The loop variable holds one entry at a time. Its key and value fields print on one line.
void main() {
var scores = {'Ana': 10, 'Ben': 20};
for (var e in scores.entries) {
print('${e.key}: ${e.value}');
}
}Visit each pair with forEach
forEach calls the function once per pair. The key arrives as the first argument and the value as the second.
void main() {
var scores = {'Ana': 10, 'Ben': 20};
scores.forEach((key, value) {
print('$key scored $value');
});
}Build a new map from entries
Each entry is mapped to a new entry with a doubled value. Map.fromEntries collects them into a fresh map, and the first map stays unchanged.
void main() {
var scores = {'Ana': 10, 'Ben': 20};
var doubled = Map.fromEntries(
scores.entries.map((e) => MapEntry(e.key, e.value * 2)),
);
print(doubled);
print(scores);
}Keys and values as lists
The keys view and the values view each print as a list. Both follow the order of the map.
void main() {
var scores = {'Ana': 10, 'Ben': 20, 'Cid': 30};
print(scores.keys.toList());
print(scores.values.toList());
}Example
void main() {
var stock = {'pens': 4, 'books': 2, 'bags': 7};
var names = <String>[];
for (var e in stock.entries) {
if (e.value > 3) {
names.add(e.key);
}
}
print(names);
}Key points
- The entries of a map hold one entry per key and value pair.
- Each entry has a key field and a value field.
- A for loop over entries reads both fields of each entry.
- forEach hands each key and value to a function.
- Map.fromEntries builds a new map from a set of entries.
- The keys and values of a map give views of just one side of each pair.
In this example, the loop reads each entry of the stock map. The key is added to the list when its value is greater than 3. Pens and bags pass the test, so their names print.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What does Map.fromEntries return?