Kinda Code
Home/Dart/How to Iterate through a Map in Flutter & Dart

How to Iterate through a Map in Flutter & Dart

Last updated: February 14, 2023

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.

Related Articles