Dart Map keys
Syntax & Examples
Syntax of Map.keys
The syntax of Map.keys property is:
Iterable<K> keys This keys property of Map the keys of this Map object.
Return Type
Map.keys returns value of type Iterable<K>.
✐ Examples
1 Get keys from a map of ages
In this example,
- We create a map named
agescontaining the ages of individuals. - We use the
keysproperty of the mapagesto get an iterable containing all the keys. - We print the keys to standard output.
Dart Program
void main() {
Map<String, int> ages = {'Alice': 30, 'Bob': 25, 'Charlie': 35};
Iterable<String> mapKeys = ages.keys;
print('Keys in the map: $mapKeys');
}Output
Keys in the map: (Alice, Bob, Charlie)
2 Get keys from a map of numbers
In this example,
- We create a map named
numberscontaining numeric mappings. - We use the
keysproperty of the mapnumbersto get an iterable containing all the keys. - We print the keys to standard output.
Dart Program
void main() {
Map<int, String> numbers = {1: 'one', 2: 'two', 3: 'three'};
Iterable<int> mapKeys = numbers.keys;
print('Keys in the map: $mapKeys');
}Output
Keys in the map: (1, 2, 3)
3 Get keys from a map of flags
In this example,
- We create a map named
flagscontaining boolean flags. - We use the
keysproperty of the mapflagsto get an iterable containing all the keys. - We print the keys to standard output.
Dart Program
void main() {
Map<String, bool> flags = {'enabled': true, 'disabled': false};
Iterable<String> mapKeys = flags.keys;
print('Keys in the map: $mapKeys');
}Output
Keys in the map: (enabled, disabled)
Summary
In this Dart tutorial, we learned about keys property of Map: the syntax and few working examples with output and detailed explanation for each example.