1.2 C
New York
Tuesday, November 28, 2023

Dart: How to remove specific Entries from a Map

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.Advertisements

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()

AdvertisementsThe 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.

Advertisements

Related Articles

Latest Articles