Skip to content
This repository was archived by the owner on Feb 27, 2026. It is now read-only.

Commit ecb2b04

Browse files
authored
Add Dart Map .cast() term entry (#8119)
* Add Dart Map .cast() term entry * Clarify description of .cast() method Updated the description to clarify that keys and values are cast to specified types. * Update cast.md ---------
1 parent 8c5db4d commit ecb2b04

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

  • content/dart/concepts/map/terms/cast
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
---
2+
Title: '.cast()'
3+
Description: 'Returns a new map with the same entries but with keys and values cast to the specified types.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Dart'
9+
- 'Map'
10+
- 'Methods'
11+
CatalogContent:
12+
- 'learn-dart'
13+
- 'paths/computer-science'
14+
---
15+
16+
In Dart, the **`.cast()`** method returns a new `Map` containing the same key–value pairs as the original map, but with the specified key and value types. The returned map performs runtime type checks when reading or writing entries. If a key or value does not match the specified types, a `TypeError` is thrown.
17+
18+
This method is commonly used when working with dynamically typed maps that need to be treated as a map with specific types.
19+
20+
## Syntax
21+
22+
```pseudo
23+
mapVariable.cast<NewKeyType, NewValueType>()
24+
```
25+
26+
`mapVariable` is the `Map` object whose entries are cast to new types.
27+
28+
**Parameters:**
29+
30+
- `NewKeyType`: The target key type to cast the map’s keys to.
31+
- `NewValueType`: The target value type to cast the map’s values to.
32+
33+
**Return value:**
34+
35+
Returns a new `Map<K, V>` view of the original map, where keys and values are cast to the specified types.
36+
37+
## Example
38+
39+
In this example, a dynamically typed map is cast to a `Map<String, int>` so its entries can be accessed with strong typing:
40+
41+
```dart
42+
void main() {
43+
Map<dynamic, dynamic> rawData = {
44+
'Alice': 90,
45+
'Bob': 85,
46+
};
47+
48+
Map<String, int> scores = rawData.cast<String, int>();
49+
50+
print(scores);
51+
}
52+
```
53+
54+
The output of this code is:
55+
56+
```shell
57+
{Alice: 90, Bob: 85}
58+
```

0 commit comments

Comments
 (0)