Dart Map cast()
Syntax & Examples


Syntax of Map.cast()

The syntax of Map.cast() method is:

 Map<RK, RV> cast<RK, RV>() 

This cast() method of Map provides a view of this map as having RK keys and RV instances, if necessary.

Return Type

Map.cast() returns value of type Map<RK, RV>.



✐ Examples

1 Cast map with dynamic values to map with int values

In this example,

  1. We create a map named originalMap with dynamic values.
  2. We then use the cast() method to cast originalMap to a map with integer values.
  3. We print the casted map to standard output.

Dart Program

void main() {
  Map&lt;String, dynamic&gt; originalMap = {'one': 1, 'two': 2, 'three': 3};
  Map&lt;String, int&gt; castedMap = originalMap.cast&lt;String, int&gt;();
  print('Casted map: $castedMap');
}

Output

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

2 Cast map with dynamic keys to map with string values

In this example,

  1. We create a map named originalMap with dynamic keys.
  2. We then use the cast() method to cast originalMap to a map with string keys.
  3. We print the casted map to standard output.

Dart Program

void main() {
  Map&lt;int, dynamic&gt; originalMap = {1: 'one', 2: 'two', 3: 'three'};
  Map&lt;int, String&gt; castedMap = originalMap.cast&lt;int, String&gt;();
  print('Casted map: $castedMap');
}

Output

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

3 Cast map with dynamic keys and values to map with string keys and values

In this example,

  1. We create a map named originalMap with dynamic keys and values.
  2. We then use the cast() method to cast originalMap to a map with string keys and values.
  3. We print the casted map to standard output.

Dart Program

void main() {
  Map&lt;String, dynamic&gt; originalMap = {'one': '1', 'two': '2', 'three': '3'};
  Map&lt;String, String&gt; castedMap = originalMap.cast&lt;String, String&gt;();
  print('Casted map: $castedMap');
}

Output

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

Summary

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