How to Iterate through a Map in Flutter & Dart

Updated: February 13, 2023 By: A Goodman Post a comment

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:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles