.clear()
Published Mar 12, 2024
Contribute to Docs
The .clear()
method in Dart is used to remove all the key-value pairs from a map, effectively making it empty. This method is useful when there is a need to remove all the elements from a map. Even if a map doesn’t have any key-value pairs, the method will not throw any error.
Syntax
map.clear()
map
: The name of the map on which the.clear()
method is called.
Example
In the following example, the .clear()
method is used to remove all the key-value pairs from the scores
map:
void main() {Map<String, int> scores = {'John': 100, 'Alice': 85, 'Bob': 92};//Clearing the 'scores' mapscores.clear();print(scores);Map<String, String> emptyMap = {};emptyMap.clear();print(emptyMap);Map<String, dynamic> user = {'name': 'John Doe', 'age': 30, 'email': '[email protected]'};user.clear();//Clearing a map and inserting different valuesuser['name'] = 'Alice';user['age'] = 28;user['email'] = '[email protected]';print(user);}
The output for the above code is:
{}{}{name: Alice, age: 28, email: [email protected]}
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.