Dart Map clear()
Syntax & Examples


Syntax of Map.clear()

The syntax of Map.clear() method is:

 void clear() 

This clear() method of Map removes all entries from the map.

Return Type

Map.clear() returns value of type void.



✐ Examples

1 Clear entries from a map

In this example,

  1. We create a map map with initial key/value pairs.
  2. We then use the clear() method to remove all entries from map.
  3. We print map after clearing it to standard output.

Dart Program

void main() {
  var map = {'a': 1, 'b': 2};
  map.clear();
  print(map);
}

Output

{}

2 Clear entries from another map

In this example,

  1. We create a map map with initial key/value pairs.
  2. We use the clear() method to remove all entries from map.
  3. We print map after clearing it to standard output.

Dart Program

void main() {
  var map = {'x': 'apple', 'y': 'banana'};
  map.clear();
  print(map);
}

Output

{}

3 Clear entries from a map of names

In this example,

  1. We create a map map with initial key/value pairs representing IDs and names.
  2. We use the clear() method to remove all entries from map.
  3. We print map after clearing it to standard output.

Dart Program

void main() {
  var map = {'id1': 'John', 'id2': 'Doe'};
  map.clear();
  print(map);
}

Output

{}

Summary

In this Dart tutorial, we learned about clear() method of Map: the syntax and few working examples with output and detailed explanation for each example.