Dart Map.fromEntries()
Syntax & Examples

Syntax of Map.fromEntries

The syntax of Map.Map.fromEntries constructor is:

Map.fromEntries(Iterable<MapEntry<K, V>> entries)

This Map.fromEntries constructor of Map creates a new map and adds all entries.

Parameters

ParameterOptional/RequiredDescription
entriesrequiredAn iterable of MapEntry objects representing key-value pairs to be added to the new map.


✐ Examples

1 Create a map from string-int pairs

In this example,

  1. We create an iterable of MapEntry objects representing key-value pairs of strings and integers.
  2. We then create a map using Map.fromEntries() with the provided entries.
  3. The resulting map contains the key-value pairs specified in the entries.
  4. We print the map to standard output.

Dart Program

void main() {
  var entries = [MapEntry('a', 1), MapEntry('b', 2), MapEntry('c', 3)];
  var map = Map.fromEntries(entries);
  print('Map from entries: $map');
}

Output

Map from entries: {a: 1, b: 2, c: 3}

2 Create a map from int-string pairs

In this example,

  1. We create an iterable of MapEntry objects representing key-value pairs of integers and strings.
  2. We then create a map using Map.fromEntries() with the provided entries.
  3. The resulting map contains the key-value pairs specified in the entries.
  4. We print the map to standard output.

Dart Program

void main() {
  var entries = [MapEntry(1, 'one'), MapEntry(2, 'two'), MapEntry(3, 'three')];
  var map = Map.fromEntries(entries);
  print('Map from entries: $map');
}

Output

Map from entries: {1: one, 2: two, 3: three}

3 Create a map from boolean-string pairs

In this example,

  1. We create an iterable of MapEntry objects representing key-value pairs of booleans and strings.
  2. We then create a map using Map.fromEntries() with the provided entries.
  3. The resulting map contains the key-value pairs specified in the entries.
  4. We print the map to standard output.

Dart Program

void main() {
  var entries = [MapEntry(true, 'yes'), MapEntry(false, 'no')];
  var map = Map.fromEntries(entries);
  print('Map from entries: $map');
}

Output

Map from entries: {true: yes, false: no}

Summary

In this Dart tutorial, we learned about Map.fromEntries constructor of Map: the syntax and few working examples with output and detailed explanation for each example.