Dart Map containsKey()
Syntax & Examples


Syntax of Map.containsKey()

The syntax of Map.containsKey() method is:

 bool containsKey(Object? key) 

This containsKey() method of Map whether this map contains the given key.

Parameters

ParameterOptional/RequiredDescription
keyrequiredthe key to check for existence in the map

Return Type

Map.containsKey() returns value of type bool.



✐ Examples

1 Check if map contains key 'one'

In this example,

  1. We create a map named map1 with string keys and integer values.
  2. We then use the containsKey() method to check if 'one' is a key in map1.
  3. As a result, the boolean value indicating whether 'one' is a key in the map is printed.

Dart Program

void main() {
  Map<String, int> map1 = {'one': 1, 'two': 2, 'three': 3};
  bool containsKeyOne = map1.containsKey('one');
  print('Contains key "one": $containsKeyOne');
}

Output

Contains key "one": true

2 Check if map contains key 4

In this example,

  1. We create a map named map2 with integer keys and string values.
  2. We then use the containsKey() method to check if 4 is a key in map2.
  3. As a result, the boolean value indicating whether 4 is a key in the map is printed.

Dart Program

void main() {
  Map<int, String> map2 = {1: 'one', 2: 'two', 3: 'three'};
  bool containsKeyFour = map2.containsKey(4);
  print('Contains key 4: $containsKeyFour');
}

Output

Contains key 4: false

3 Check if map contains key 'banana'

In this example,

  1. We create a map named map3 with string keys and string values.
  2. We then use the containsKey() method to check if 'banana' is a key in map3.
  3. As a result, the boolean value indicating whether 'banana' is a key in the map is printed.

Dart Program

void main() {
  Map<String, String> map3 = {'apple': 'red', 'banana': 'yellow', 'cherry': 'red'};
  bool containsKeyBanana = map3.containsKey('banana');
  print('Contains key "banana": $containsKeyBanana');
}

Output

Contains key "banana": true

Summary

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