Dart Map.of()
Syntax & Examples
Syntax of Map.of
The syntax of Map.Map.of constructor is:
Map.of(Map<K, V> other)
This Map.of constructor of Map creates a LinkedHashMap
with the same keys and values as other
.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
other | required | The map whose keys and values will be used to create the new map. |
✐ Examples
1 Create a map from integer-string pairs
In this example,
- We create a map named
map1
containing integer-string pairs. - We then create a new map using
Map.of()
withmap1
as the argument. - The new map contains the same keys and values as
map1
. - We print the new map to standard output.
Dart Program
void main() {
var map1 = {1: 'one', 2: 'two', 3: 'three'};
var newMap = Map.of(map1);
print('New map: $newMap');
}
Output
New map: {1: one, 2: two, 3: three}
2 Create a map from string-integer pairs
In this example,
- We create a map named
map2
containing string-integer pairs. - We then create a new map using
Map.of()
withmap2
as the argument. - The new map contains the same keys and values as
map2
. - We print the new map to standard output.
Dart Program
void main() {
var map2 = {'a': 1, 'b': 2, 'c': 3};
var newMap = Map.of(map2);
print('New map: $newMap');
}
Output
New map: {a: 1, b: 2, c: 3}
3 Create a map from string-string pairs
In this example,
- We create a map named
map3
containing string-string pairs. - We then create a new map using
Map.of()
withmap3
as the argument. - The new map contains the same keys and values as
map3
. - We print the new map to standard output.
Dart Program
void main() {
var map3 = {'x': 'apple', 'y': 'banana', 'z': 'cherry'};
var newMap = Map.of(map3);
print('New map: $newMap');
}
Output
New map: {x: apple, y: banana, z: cherry}
Summary
In this Dart tutorial, we learned about Map.of constructor of Map: the syntax and few working examples with output and detailed explanation for each example.