To remove a key-value pair from a map in Dart, you can use the remove method. This method allows you to remove the key-value pair associated with the specified key.
We can remove a key-value pair from a map in Dart using the remove method, which removes the key-value pair associated with the specified key.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.remove
method to remove the key-value pair associated with the key 'two'
. The remove
method removes the key-value pair from the map and returns the value associated with the removed key.print
function to verify that the key-value pair has been removed.void main() {
// Declare and initialize a map
Map<String, int> myMap = {
'one': 1,
'two': 2,
'three': 3
};
// Remove a key-value pair using remove method
myMap.remove('two');
// Print the contents of the map
print(myMap);
}
{one: 1, three: 3}
We can handle the case where a key is not found in a map in Dart using the remove method, which returns null if the key is not present.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.remove
method to attempt to remove the key-value pair associated with the key 'four'
. The remove
method returns null if the key is not found.print
function to verify that the map is unchanged.void main() {
// Declare and initialize a map
Map<String, int> myMap = {
'one': 1,
'two': 2,
'three': 3
};
// Attempt to remove a non-existent key-value pair using remove method
myMap.remove('four');
// Print the contents of the map
print(myMap);
}
{one: 1, two: 2, three: 3}
We can remove multiple key-value pairs from a map in Dart using the remove method, which removes the key-value pairs associated with the specified keys.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.remove
method to remove the key-value pairs associated with the keys 'one'
and 'three'
. The remove
method removes the key-value pairs from the map and returns the value associated with the removed keys.print
function to verify that the key-value pairs have been removed.void main() {
// Declare and initialize a map
Map<String, int> myMap = {
'one': 1,
'two': 2,
'three': 3
};
// Remove multiple key-value pairs using remove method
myMap.remove('one');
myMap.remove('three');
// Print the contents of the map
print(myMap);
}
{two: 2}
In this tutorial, we learned How to Remove a Key-Value Pair from a Map in Dart language with well detailed examples.