How to Iterate through a Map in Flutter & Dart

Last updated on November 5, 2020 A Goodman Loading... Post a comment

This article shows you 2 ways to iterate through a map in Flutter / Dart.

Using forEach

Sample code:

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){
    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:

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){
    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:

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){
    print(value);
  } 
}

Output:

1
Fry Pan
40
Hard anodized aluminum construction for durability
black
12 inch

Related Articles

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x