Dart Map.identity()
Syntax & Examples

Syntax of Map.identity

The syntax of Map.Map.identity constructor is:

Map.identity()

This Map.identity constructor of Map creates an identity map with the default implementation, LinkedHashMap.



✐ Examples

1 Create an identity map of integers to strings

In this example,

  1. We create an empty identity map map.
  2. We then add key-value pairs to the map where the keys are integers and the values are strings.
  3. Since this is an identity map, the keys are exactly the same as the ones assigned, and the map preserves insertion order.
  4. We print the resulting map to standard output.

Dart Program

void main() {
  Map<int, String> map = Map.identity();
  map[1] = 'one';
  map[2] = 'two';
  map[3] = 'three';
  print(map);
}

Output

{1: one, 2: two, 3: three}

2 Create an identity map of strings to integers

In this example,

  1. We create an empty identity map map.
  2. We then add key-value pairs to the map where the keys are strings and the values are integers.
  3. Since this is an identity map, the keys are exactly the same as the ones assigned, and the map preserves insertion order.
  4. We print the resulting map to standard output.

Dart Program

void main() {
  Map<String, int> map = Map.identity();
  map['a'] = 1;
  map['b'] = 2;
  map['c'] = 3;
  print(map);
}

Output

{a: 1, b: 2, c: 3}

3 Create an identity map of strings to strings

In this example,

  1. We create an empty identity map map.
  2. We then add key-value pairs to the map where both keys and values are strings.
  3. Since this is an identity map, the keys are exactly the same as the ones assigned, and the map preserves insertion order.
  4. We print the resulting map to standard output.

Dart Program

void main() {
  Map<String, String> map = Map.identity();
  map['key1'] = 'value1';
  map['key2'] = 'value2';
  map['key3'] = 'value3';
  print(map);
}

Output

{key1: value1, key2: value2, key3: value3}

Summary

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