How to check for Map keys and values in Dart
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.
Syntax
map_name.containsKey(key)
Note:
map_nameis 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.
Syntax
map_name.containsValue(value)
Note:
map_nameis 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 map1Map map1 = {1: 'Maria', 2: 'Harrison', 3: 'Paul', 4: 'Rejoice'};// Checks for key in map1print('Is key 1 in the map:${map1.containsKey(1)}');print('Is key 5 in the map:${map1.containsKey(5)}');// Checks for values in map1print('Is the value "Maria" in the map:${map1.containsValue('Maria')}');print('Is the value "Helen" in the map:${map1.containsValue('Helen')}');}