The syntax of Map.containsKey() method is:
bool containsKey(Object? key)
This containsKey() method of Map whether this map contains the given key
.
Parameter | Optional/Required | Description |
---|---|---|
key | required | the key to check for existence in the map |
Map.containsKey() returns value of type bool
.
In this example,
map1
with string keys and integer values.containsKey()
method to check if 'one' is a key in map1
.void main() {
Map<String, int> map1 = {'one': 1, 'two': 2, 'three': 3};
bool containsKeyOne = map1.containsKey('one');
print('Contains key "one": $containsKeyOne');
}
Contains key "one": true
In this example,
map2
with integer keys and string values.containsKey()
method to check if 4 is a key in map2
.void main() {
Map<int, String> map2 = {1: 'one', 2: 'two', 3: 'three'};
bool containsKeyFour = map2.containsKey(4);
print('Contains key 4: $containsKeyFour');
}
Contains key 4: false
In this example,
map3
with string keys and string values.containsKey()
method to check if 'banana' is a key in map3
.void main() {
Map<String, String> map3 = {'apple': 'red', 'banana': 'yellow', 'cherry': 'red'};
bool containsKeyBanana = map3.containsKey('banana');
print('Contains key "banana": $containsKeyBanana');
}
Contains key "banana": true
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.