.containsKey()

andersooi's avatar
Published Mar 13, 2024
Contribute to Docs

In Dart, the .containsKey() method is an efficient and quick way to check if a particular key is present in a Map object.

Syntax

mapVariable.containsKey(key)
  • mapVariable: The name of the Map object to be checked.
  • key: The key to be checked within the Map object.

Examples

In the following example, the .containsKey() method is used to check if the specified keys are present in the Map object:

void main() {
Map<String, String> nbaTeams = {
'BOS': 'Boston Celtics',
'GSW': 'Golden State Warriors',
'LAL': 'Los Angeles Lakers'
};
print(nbaTeams.containsKey('BOS'));
print(nbaTeams.containsKey('OKC'));
}

Here is the output for the above example:

true
false

The .containsKey() method can also work with keys of different data types:

void main() {
Map<int, String> runnerPositions = {
1: 'Andrew',
2: 'Benedict',
3: 'Charlie'
};
print(runnerPositions.containsKey(1));
print(runnerPositions.containsKey(4));
}

The above example gives the following output:

true
false

All contributors

Contribute to Docs

Learn Dart on Codecademy