Dart Map.from()
Syntax & Examples

Syntax of Map.from

The syntax of Map.Map.from constructor is:

Map.from(Map other)

This Map.from constructor of Map creates a LinkedHashMap with the same keys and values as other.

Parameters

ParameterOptional/RequiredDescription
otherrequiredthe map to copy keys and values from


✐ Examples

1 Copy a map of integers to strings

In this example,

  1. We create a map other containing integer keys and string values.
  2. We then use the Map.from() constructor to create a new map copiedMap with the same keys and values as other.
  3. We print the copied map to standard output.

Dart Program

void main() {
  Map<int, String> other = {1: 'one', 2: 'two', 3: 'three'};
  Map<int, String> copiedMap = Map.from(other);
  print(copiedMap);
}

Output

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

2 Copy a map of strings to integers

In this example,

  1. We create a map other containing string keys and integer values.
  2. We then use the Map.from() constructor to create a new map copiedMap with the same keys and values as other.
  3. We print the copied map to standard output.

Dart Program

void main() {
  Map<String, int> other = {'a': 1, 'b': 2, 'c': 3};
  Map<String, int> copiedMap = Map.from(other);
  print(copiedMap);
}

Output

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

3 Copy a map of strings to strings

In this example,

  1. We create a map other containing string keys and string values.
  2. We then use the Map.from() constructor to create a new map copiedMap with the same keys and values as other.
  3. We print the copied map to standard output.

Dart Program

void main() {
  Map<String, String> other = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'};
  Map<String, String> copiedMap = Map.from(other);
  print(copiedMap);
}

Output

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

Summary

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