Dart Map remove()
Syntax & Examples


Syntax of Map.remove()

The syntax of Map.remove() method is:

 V? remove(Object? key) 

This remove() method of Map removes key and its associated value, if present, from the map.

Parameters

ParameterOptional/RequiredDescription
keyrequiredthe key to be removed from the map

Return Type

Map.remove() returns value of type V?.



✐ Examples

1 Remove key 'b' from map

In this example,

  1. We create a map named map with key-value pairs {'a': 1, 'b': 2, 'c': 3}.
  2. We then remove the key 'b' from the map using the remove() method.
  3. The resulting map after removal is printed to standard output.

Dart Program

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

Output

{a: 1, c: 3}

2 Remove key 'y' and get its value

In this example,

  1. We create a map named map with key-value pairs {'x': 'apple', 'y': 'banana', 'z': 'cherry'}.
  2. We then remove the key 'y' from the map using the remove() method and store the removed value in removedValue.
  3. The removed value is printed to standard output.

Dart Program

void main() {
  var map = {'x': 'apple', 'y': 'banana', 'z': 'cherry'};
  var removedValue = map.remove('y');
  print('Removed value: $removedValue');
}

Output

Removed value: banana

3 Remove key-value pair with key 2

In this example,

  1. We create a map named map with key-value pairs {1: 'one', 2: 'two', 3: 'three'}.
  2. We define removedKey as 2.
  3. We then remove the entry with key 2 from the map using the remove() method and store the removed value in removedValue.
  4. The removed key-value pair is printed to standard output.

Dart Program

void main() {
  var map = {1: 'one', 2: 'two', 3: 'three'};
  var removedKey = 2;
  var removedValue = map.remove(removedKey);
  print('Removed entry: ($removedKey, $removedValue)');
}

Output

Removed entry: (2, two)

Summary

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