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
| 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 |
✐ Examples
1 Create a map of numbers with formatted values
In this example,
- We have a list
numberscontaining integers. - We use the
Map.fromIterable()constructor to create a mapmapwhere the keys are the numbers themselves and the values are formatted strings. - We provide functions to compute both keys and values based on the elements in the
numberslist. - 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,
- We have a list
characterscontaining strings. - We use the
Map.fromIterable()constructor to create a mapmapwhere the keys are the characters themselves and the values are their Unicode values. - We provide functions to compute both keys and values based on the elements in the
characterslist. - 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,
- We have a list
wordscontaining strings. - We use the
Map.fromIterable()constructor to create a mapmapwhere the keys are the words themselves and the values are their lengths. - We provide functions to compute both keys and values based on the elements in the
wordslist. - 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.