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.
Map.cast() returns value of type Map<RK, RV>
.
In this example,
originalMap
with dynamic values.cast()
method to cast originalMap
to a map with integer values.void main() {
Map<String, dynamic> originalMap = {'one': 1, 'two': 2, 'three': 3};
Map<String, int> castedMap = originalMap.cast<String, int>();
print('Casted map: $castedMap');
}
Casted map: {one: 1, two: 2, three: 3}
In this example,
originalMap
with dynamic keys.cast()
method to cast originalMap
to a map with string keys.void main() {
Map<int, dynamic> originalMap = {1: 'one', 2: 'two', 3: 'three'};
Map<int, String> castedMap = originalMap.cast<int, String>();
print('Casted map: $castedMap');
}
Casted map: {1: one, 2: two, 3: three}
In this example,
originalMap
with dynamic keys and values.cast()
method to cast originalMap
to a map with string keys and values.void main() {
Map<String, dynamic> originalMap = {'one': '1', 'two': '2', 'three': '3'};
Map<String, String> castedMap = originalMap.cast<String, String>();
print('Casted map: $castedMap');
}
Casted map: {one: 1, two: 2, three: 3}
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.