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,
- We create a map named
originalMap
with dynamic values. - We then use the
cast()
method to castoriginalMap
to a map with integer values. - We print the casted map to standard output.
Dart Program
void main() {
Map<String, dynamic> originalMap = {'one': 1, 'two': 2, 'three': 3};
Map<String, int> castedMap = originalMap.cast<String, int>();
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,
- We create a map named
originalMap
with dynamic keys. - We then use the
cast()
method to castoriginalMap
to a map with string keys. - We print the casted map to standard output.
Dart Program
void main() {
Map<int, dynamic> originalMap = {1: 'one', 2: 'two', 3: 'three'};
Map<int, String> castedMap = originalMap.cast<int, String>();
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,
- We create a map named
originalMap
with dynamic keys and values. - We then use the
cast()
method to castoriginalMap
to a map with string keys and values. - We print the casted map to standard output.
Dart Program
void main() {
Map<String, dynamic> originalMap = {'one': '1', 'two': '2', 'three': '3'};
Map<String, String> castedMap = originalMap.cast<String, String>();
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.