To convert a map to an array of keys in Dart, you can use the keys property. This property returns an iterable of all the keys in the map, which can be converted to a list.
We can convert a map to an array of keys in Dart using the keys property, which provides an iterable of all keys in the map. We can then convert this iterable to a list.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.keys
property to get an iterable of the keys in the map.toList
method.keysList
.print
function to verify the conversion.void main() {
// Declare and initialize a map
Map<String, int> myMap = {
'one': 1,
'two': 2,
'three': 3
};
// Convert map to an array of keys
List<String> keysList = myMap.keys.toList();
// Print the keys
print('Keys: $keysList');
}
Keys: [one, two, three]
We can also convert an empty map to an array of keys in Dart using the keys property, which returns an empty list when the map is empty.
For example,
emptyMap
with string keys and integer values.keys
property to get an iterable of the keys in the empty map.toList
method.emptyKeysList
.print
function to verify that the list is empty.void main() {
// Declare an empty map
Map<String, int> emptyMap = {};
// Convert empty map to an array of keys
List<String> emptyKeysList = emptyMap.keys.toList();
// Print the keys
print('Keys: $emptyKeysList');
}
Keys: []
We can convert a map to an array of keys in Dart after adding elements using the keys property, which provides an updated iterable of all keys in the map.
For example,
dynamicMap
with string keys and integer values.keys
property to get an iterable of the keys in the map after adding elements.toList
method.dynamicKeysList
.print
function to verify the updated list of keys.void main() {
// Declare an empty map
Map<String, int> dynamicMap = {};
// Add elements to the map
dynamicMap['one'] = 1;
dynamicMap['two'] = 2;
dynamicMap['three'] = 3;
// Convert map to an array of keys after adding elements
List<String> dynamicKeysList = dynamicMap.keys.toList();
// Print the keys
print('Keys: $dynamicKeysList');
}
Keys: [one, two, three]
In this tutorial, we learned How to Convert a Map to an Array of Keys in Dart language with well detailed examples.