Dart: How to remove specific Entries from a Map

Last updated on August 17, 2021 A Goodman Loading... Post a comment

In Dart, you can remove key/value pairs from a given map by using one of the following methods:

  • remove(): Removes the entry that associated with the provided key. No error will occur even if the provided key doesn’t exist.
  • removeWhere(): Removes all entries that satisfy the given conditions.

For more clarity, see the examples below.

Example 1: Using remove()

This code snippet removes the entries that contain keys: age, occupation, hometown.

// main.dart
Map<String, dynamic> person = {
  'name': 'John Doe',
  'age': 39,
  'occupation': 'Thief',
  'hometown': 'Unknown',
  'isMarried': false
};

void main() {
  person.remove('age');
  person.remove('occupation');
  person.remove('hometown');
  print(person);
}

Output:

name: John Doe, isMarried: false}

Example 2: Using removeWhere()

The following code removes entries with values of null or a whose key is secret:

// main.dart
Map<String, dynamic> project = {
  'title': 'KindaCode.com: A Programming Website',
  'age': 5,
  'language': 'English',
  'technologies': 'Unknown',
  'traffic': null,
  'contact': null,
  'secret': 'Flying pan'
};

void main() {
  project.removeWhere((key, value) => value == null || key == 'secret');
  print(project);
}

Output:

{title: KindaCode.com: A Programming Website, age: 5, language: English, technologies: Unknown}

Futher Reading

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like