.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' map
scores.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 values
user['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]}

All contributors

Looking to contribute?

Learn Dart on Codecademy