10.4 C
New York
Wednesday, November 22, 2023

How to Iterate through a Map in Flutter & Dart

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

Using forEach

Sample code:Advertisements

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

AdvertisementsIf 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

Latest Articles