Dart Map.unmodifiable()
Syntax & Examples

Syntax of Map.unmodifiable

The syntax of Map.Map.unmodifiable constructor is:

Map.unmodifiable(Map other)

This Map.unmodifiable constructor of Map creates an unmodifiable hash-based map containing the entries of other.

Parameters

ParameterOptional/RequiredDescription
otherrequiredThe map whose entries will be included in the new unmodifiable map.


✐ Examples

1 Create an unmodifiable map from integer-string pairs

In this example,

  1. We create a map named map1 containing integer-string pairs.
  2. We then create an unmodifiable map using Map.unmodifiable() with map1 as the argument.
  3. The unmodifiable map contains the same entries as map1.
  4. We print the unmodifiable map to standard output.

Dart Program

void main() {
  var map1 = {1: 'one', 2: 'two', 3: 'three'};
  var unmodifiableMap = Map.unmodifiable(map1);
  print('Unmodifiable map: $unmodifiableMap');
}

Output

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

2 Create an unmodifiable map from string-integer pairs

In this example,

  1. We create a map named map2 containing string-integer pairs.
  2. We then create an unmodifiable map using Map.unmodifiable() with map2 as the argument.
  3. The unmodifiable map contains the same entries as map2.
  4. We print the unmodifiable map to standard output.

Dart Program

void main() {
  var map2 = {'a': 1, 'b': 2, 'c': 3};
  var unmodifiableMap = Map.unmodifiable(map2);
  print('Unmodifiable map: $unmodifiableMap');
}

Output

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

3 Create an unmodifiable map from string-string pairs

In this example,

  1. We create a map named map3 containing string-string pairs.
  2. We then create an unmodifiable map using Map.unmodifiable() with map3 as the argument.
  3. The unmodifiable map contains the same entries as map3.
  4. We print the unmodifiable map to standard output.

Dart Program

void main() {
  var map3 = {'x': 'apple', 'y': 'banana', 'z': 'cherry'};
  var unmodifiableMap = Map.unmodifiable(map3);
  print('Unmodifiable map: $unmodifiableMap');
}

Output

Unmodifiable map: {x: apple, y: banana, z: cherry}

Summary

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