Dart/Flutter - Get All Keys And Values from a Map

This tutorial shows you how to get the list of all keys and values from a Map using Dart.

Map is one of the data types supported by Dart. It allows you to store a collection of key-value pairs. The key of a Map must be unique as it's used as the identifier to find an entry. Map is frequently used for data that needs frequent lookup. If you have a Map and you need to get the list of keys, values, or both, you can read the examples in this tutorial. The examples also work in any Dart framework including Flutter.

First, create a Map that contains some entries.

  Map<String, Object> options = {
    "color": "teal",
    "size": 100,
    "isNew": true,
  };

Get All Keys

Dart's Map class has a keys property which returns an Iterable containing the list of keys. The order of the keys and values depend on how you create the Map. For example, whether you create it using LinkedHashMap or SplayTreeMap. From the Iterable, you can iterate over the keys by using a for loop. While iterating, the Map should not be modified to avoid breaking the iteration.

  Iterable<String> keys = options.keys;
  for (final key in keys) {
    print(key);
  }

Output:

  color
  size
  isNew

Get All Values

For getting the list of values, the property you have to access is values. It also returns an Iterable and you can iterate over the values. The order of the values is the same as their corresponding keys. You should not modify the Map during the iteration to avoid breaking the iteration.

  Iterable<Object> values = options.values;
  for (final value in values) {
    print(value);
  }

Output:

  teal
  100
  true

Get All Keys And Values

If you need to get both the list of keys and values, you can try to access the entries property. It returns an Iterable whose element type is MapEntry. From a MapEntry, you can get both the key and the value.

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

Output:

  (color, teal)
  (size, 100)
  (isNew, true)

Summary

Getting the keys and the values of a Map can be done from the keys and values properties respectively. If you need to get both the values and the keys, it can be obtained from the entries property.

You can also read about: