Dart Map.fromIterable()
Syntax & Examples


Syntax of Map.fromIterable

The syntax of Map.Map.fromIterable constructor is:

Map.fromIterable(Iterable iterable, {K key(dynamic element)?, V value(dynamic element)?})

This Map.fromIterable constructor of Map creates a Map instance in which the keys and values are computed from the iterable.

Parameters

ParameterOptional/RequiredDescription
iterablerequiredthe iterable to create the map from
key(dynamic element)optionala function that computes the key for each element in the iterable
value(dynamic element)optionala function that computes the value for each element in the iterable


✐ Examples

1 Create a map of numbers with formatted values

In this example,

  1. We have a list numbers containing integers.
  2. We use the Map.fromIterable() constructor to create a map map where the keys are the numbers themselves and the values are formatted strings.
  3. We provide functions to compute both keys and values based on the elements in the numbers list.
  4. We print the resulting map to standard output.

Dart Program

void main() {
  List<int> numbers = [1, 2, 3, 4, 5];
  Map<int, String> map = Map.fromIterable(numbers, key: (item) => item, value: (item) => 'Value${item}');
  print(map);
}

Output

{1: Value1, 2: Value2, 3: Value3, 4: Value4, 5: Value5}

2 Create a map of characters with their Unicode values

In this example,

  1. We have a list characters containing strings.
  2. We use the Map.fromIterable() constructor to create a map map where the keys are the characters themselves and the values are their Unicode values.
  3. We provide functions to compute both keys and values based on the elements in the characters list.
  4. We print the resulting map to standard output.

Dart Program

void main() {
  List<String> characters = ['a', 'b', 'c'];
  Map<String, int> map = Map.fromIterable(characters, key: (item) => item, value: (item) => item.codeUnitAt(0));
  print(map);
}

Output

{a: 97, b: 98, c: 99}

3 Create a map of words with their lengths

In this example,

  1. We have a list words containing strings.
  2. We use the Map.fromIterable() constructor to create a map map where the keys are the words themselves and the values are their lengths.
  3. We provide functions to compute both keys and values based on the elements in the words list.
  4. We print the resulting map to standard output.

Dart Program

void main() {
  List<String> words = ['apple', 'banana', 'cherry'];
  Map<String, int> map = Map.fromIterable(words, key: (item) => item, value: (item) => item.length);
  print(map);
}

Output

{apple: 5, banana: 6, cherry: 6}

Summary

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