Dart/Flutter - Iterate Over a Map

This tutorial shows you how to iterate over the entries of a Map using Dart.

If you code using Dart and you have key-value pairs data, Map can be your choice to store the data. If you already have a Map variable, you may want to iterate over the entries to get the keys and the values. In Dart, there are several ways to do it. Below are the examples that also work in Flutter or any Dart framework.

First, let's create a Map with initial values.

  Map<String, Object> details = {
    "name": "Twice",
    "members": 9,
    "isCute": false,
  };

Using for Loop

Map has a property named entries which returns an Iterable of entries. An Iterable in Dart can be iterated using a for loop as shown below.

  Iterable<MapEntry<String, Object>> entries = details.entries;
for (final entry in entries) { print('(${entry.key}, ${entry.value})'); }

Output:

  (name, Twice)
  (members, 9)
  (isCute, false)

Using Iterator

Dart's Iterable has iterator property. You can iterate using the Iterator by calling moveNext() to go to the next entry. The value of the current entry can be obtained from the current property.

  Iterator iterator = details.entries.iterator;
  while (iterator.moveNext()) {
    MapEntry<String, Object> entry = iterator.current;
    print('(${entry.key}, ${entry.value})');
  }

Output:

  (name, Twice)
  (members, 9)
  (isCute, false)

Using forEach Method

The Map class has a forEach method that allows you to perform iteration. You need to pass a function with two parameters, with the key as the first one and the value as the last one.

  details.forEach((key, value) {
    print('($key, $value)');
  });

Output:

  (name, Twice)
  (members, 9)
  (isCute, false)

Using map Method

If the goal of the iteration is to return a new Map by transforming the entries of an existing Map, the most suitable method of the Map class to use is map. You have to pass a function which accepts two arguments, the key and the value. The function will be invoked for each iterated entry. It needs to return a MapEntry by transforming the key or the value of an existing entry. For example, the code below formats the keys to uppercase.

Despite it always creates a new Map, you have to be careful that modifying a mutable object may also modify the object of the original Map. As a solution, consider performing a deep clone.

  Map<String, Object> formatted = details.map((key, value) {
    return MapEntry(key.toUpperCase(), value);
  });
  print(formatted);

Output:

  {NAME: Twice, MEMBERS: 9, ISCUTE: false}

Summary

In this tutorial, we have learned several ways to iterate through a Map. You can get the entries and use a for loop or an Iterator. Another alternative is using the forEach method. If the purpose of the iteration is for creating a new Map, you can use the map method. Keep in mind that the order of the entries depend on the used Map implementation (HashMap, LinkedHashMap, or SplayTreeMap.

You can also read about: