This succinct, practical article shows you 2 different ways to iterate through a map in Flutter and Dart.
Using forEach
Sample code:
import 'package:flutter/foundation.dart';
final Map product = {
'id': 1,
'name': 'Fry Pan',
'price': 40,
'description': 'Hard anodized aluminum construction for durability',
'color': 'black',
'size': '12 inch',
};
void main() {
product.forEach((key, value) {
if (kDebugMode) {
print('Key: $key');
print('Value: $value');
print('------------------------------');
}
});
}
Output:
Key: id
Value: 1
------------------------------
Key: name
Value: Fry Pan
------------------------------
Key: price
Value: 40
------------------------------
Key: description
Value: Hard anodized aluminum construction for durability
------------------------------
Key: color
Value: black
------------------------------
Key: size
Value: 12 inch
------------------------------
Using for
Sample code:
import 'package:flutter/foundation.dart';
final Map product = {
'id': 1,
'name': 'Fry Pan',
'price': 40,
'description': 'Hard anodized aluminum construction for durability',
'color': 'black',
'size': '12 inch',
};
void main() {
for (var key in product.keys) {
if (kDebugMode) {
print('Key : $key');
print('Value: ${product[key]}');
print('\n');
}
}
}
Output:
Key : id
Value: 1
Key : name
Value: Fry Pan
Key : price
Value: 40
Key : description
Value: Hard anodized aluminum construction for durability
Key : color
Value: black
Key : size
Value: 12 inch
If you only want to iterate through map values, use this:
import 'package:flutter/foundation.dart';
final Map product = {
'id': 1,
'name': 'Fry Pan',
'price': 40,
'description': 'Hard anodized aluminum construction for durability',
'color': 'black',
'size': '12 inch',
};
void main() {
for (var value in product.values) {
if (kDebugMode) {
print(value);
}
}
}
Output:
1
Fry Pan
40
Hard anodized aluminum construction for durability
black
12 inch
That’s it. Further reading:
- Flutter: Ways to Compare 2 Deep Nested Maps
- Dart: Convert Class Instances (Objects) to Maps and Vice Versa
- Dart: How to remove specific Entries from a Map
- Flutter: ExpansionPanelList and ExpansionPanelList.radio examples
- Flutter AnimatedList – Tutorial and Examples
- Dart & Flutter: Get the Index of a Specific Element in a List
You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.