Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
dart

How to check for Map keys and values in Dart

Maria Elijah

We can use the map.containsKey() and map.containsValue() methods to check for the existence of keys and values in a Map.

map.containsKey

In Dart, the map.containsKey() method checks if a particular key is present in the given Map.

Visual illustration of the map.containsKey() method

Syntax

map_name.containsKey(key)

Note: map_name is the name of the map.

Parameters

The map.containsKey() function requires a key to be found in the map.

Return value

The map.containsKey() method returns true if the key exists in the map; otherwise, it returns false.

map.containsValue()

In Dart, the map.containsValue() method checks if a particular value is in the given Map.

Visual illustration of the map.containsValue() method

Syntax

map_name.containsValue(value)

Note: map_name is the name of the map.

Parameters

The map.containsValue() function requires a value to be searched for in the map.

Return value

The map.containsValue() method returns true if the value exists in the map; otherwise, it returns false.

Code


void main() {
  // Creating Map named map1
  Map map1 = {1: 'Maria', 2: 'Harrison', 3: 'Paul', 4: 'Rejoice'};

  // Checks for key in map1
  print('Is key 1 in the map:${map1.containsKey(1)}');   
  print('Is key 5 in the map:${map1.containsKey(5)}');

   // Checks for values in map1
  print('Is the value "Maria" in the map:${map1.containsValue('Maria')}');   
  print('Is the value "Helen" in the map:${map1.containsValue('Helen')}');
}
The map.containsKey() & map.containsValue() functions

RELATED TAGS

communitycreator
dart
RELATED COURSES

View all Courses

Keep Exploring