To clear all key-value pairs from a map in Dart, you can use the clear method. This method removes all elements from the map, leaving it empty.
We can clear all key-value pairs from a map in Dart using the clear method, which removes all elements from the map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.clear
method to remove all key-value pairs from the map.length
property to verify that the map is empty.void main() {
// Declare and initialize a map
Map<String, int> myMap = {
'one': 1,
'two': 2,
'three': 3
};
// Clear all key-value pairs using clear method
myMap.clear();
// Print the length of the map
print('Length of the map after clearing: ${myMap.length}');
}
Length of the map after clearing: 0
We can use the clear method on an already empty map in Dart, and it will still leave the map empty.
For example,
myMap
. In this example, the map has string keys and integer values.clear
method to remove all key-value pairs from the map, even though it is already empty.length
property to verify that the map is still empty.void main() {
// Declare and initialize an empty map
Map<String, int> myMap = {};
// Clear the map using clear method
myMap.clear();
// Print the length of the map
print('Length of the map after clearing: ${myMap.length}');
}
Length of the map after clearing: 0
We can insert key-value pairs into a map and then clear all key-value pairs using the clear method.
For example,
myMap
and inserting some key-value pairs into it. In this example, the map has string keys and integer values.clear
method to remove all key-value pairs from the map.length
property to verify that the map is empty.void main() {
// Declare and initialize a map
Map<String, int> myMap = {};
myMap['one'] = 1;
myMap['two'] = 2;
myMap['three'] = 3;
// Clear all key-value pairs using clear method
myMap.clear();
// Print the length of the map
print('Length of the map after clearing: ${myMap.length}');
}
Length of the map after clearing: 0
In this tutorial, we learned How to Clear All Key-Value Pairs from a Map in Dart language with well detailed examples.