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

ParameterOptional/RequiredDescription
otherrequiredThe 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,

  1. We create a map named map1 containing integer-string pairs.
  2. We then create a new map using Map.of() with map1 as the argument.
  3. The new map contains the same keys and values as map1.
  4. 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,

  1. We create a map named map2 containing string-integer pairs.
  2. We then create a new map using Map.of() with map2 as the argument.
  3. The new map contains the same keys and values as map2.
  4. 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,

  1. We create a map named map3 containing string-string pairs.
  2. We then create a new map using Map.of() with map3 as the argument.
  3. The new map contains the same keys and values as map3.
  4. 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.