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
.
Parameter | Optional/Required | Description |
---|---|---|
iterable | required | the iterable to create the map from |
key(dynamic element) | optional | a function that computes the key for each element in the iterable |
value(dynamic element) | optional | a function that computes the value for each element in the iterable |
In this example,
numbers
containing integers.Map.fromIterable()
constructor to create a map map
where the keys are the numbers themselves and the values are formatted strings.numbers
list.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);
}
{1: Value1, 2: Value2, 3: Value3, 4: Value4, 5: Value5}
In this example,
characters
containing strings.Map.fromIterable()
constructor to create a map map
where the keys are the characters themselves and the values are their Unicode values.characters
list.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);
}
{a: 97, b: 98, c: 99}
In this example,
words
containing strings.Map.fromIterable()
constructor to create a map map
where the keys are the words themselves and the values are their lengths.words
list.void main() {
List<String> words = ['apple', 'banana', 'cherry'];
Map<String, int> map = Map.fromIterable(words, key: (item) => item, value: (item) => item.length);
print(map);
}
{apple: 5, banana: 6, cherry: 6}
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.