To check if a key exists in a map in Dart, you can use the containsKey method. This method returns a boolean value indicating whether the map contains the specified key.
We can check if a key exists in a map in Dart using the containsKey method, which returns true if the map contains the specified key and false otherwise.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.containsKey
method to check for a specific key in the map. The containsKey
method returns a boolean value indicating whether the map contains the specified key.print
function.void main() {
// Declare and initialize a map
Map<String, int> myMap = {
'one': 1,
'two': 2,
'three': 3
};
// Check if a key exists using containsKey method
bool keyExists = myMap.containsKey('two');
// Print the result
print('Does key "two" exist? $keyExists');
}
Does key "two" exist? true
We can check if a key does not exist in a map in Dart using the containsKey method, which returns false if the map does not contain the specified key.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.containsKey
method to check for a specific key in the map. The containsKey
method returns a boolean value indicating whether the map contains the specified key.print
function.void main() {
// Declare and initialize a map
Map<String, int> myMap = {
'one': 1,
'two': 2,
'three': 3
};
// Check if a key does not exist using containsKey method
bool keyExists = myMap.containsKey('four');
// Print the result
print('Does key "four" exist? $keyExists');
}
Does key "four" exist? false
We can check if multiple keys exist in a map in Dart using the containsKey method, which returns true if the map contains the specified key and false otherwise.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.containsKey
method to check for multiple keys in the map. The containsKey
method returns a boolean value indicating whether the map contains the specified key.print
function.void main() {
// Declare and initialize a map
Map<String, int> myMap = {
'one': 1,
'two': 2,
'three': 3
};
// Check if multiple keys exist using containsKey method
bool keyExistsOne = myMap.containsKey('one');
bool keyExistsFour = myMap.containsKey('four');
// Print the results
print('Does key "one" exist? $keyExistsOne');
print('Does key "four" exist? $keyExistsFour');
}
Does key "one" exist? true Does key "four" exist? false
In this tutorial, we learned How to Check if a Key Exists in a Map in Dart language with well detailed examples.