Map containsKey()

Map containsKey() method checks if the given key is present in this Map. The method returns a boolean value of true if the given key is present in this Map, or false if not.

Syntax

The syntax to check if the key key is present in the Map map1 is

</>
Copy
map1.containsKey(key);

The method returns boolean value.

Examples

Check if the key ‘apple’ is present in Map

In the following Dart Program, we take a Map map1 and check if the key 'apple' is present in this Map map1, using Map.containsKey() method.

main.dart

</>
Copy
void main() {
    var map1 = {'apple': 25, 'banana': 10, 'cherry': 6};
    var key = 'apple';

    if ( map1.containsKey(key) ) {
        print('The key is present in this Map.');
    } else {
        print('The key is not present in this Map.');
    }
}

Output

The key is present in this Map.

Since, the given key is present in this Map, containsKey() returned true.

Check if the key ‘mango’ is present in Map

In the following Dart Program, we take a Map map1 and check if the key 'mango' is present in this Map map1, using Map.containsKey() method.

main.dart

</>
Copy
void main() {
    var map1 = {'apple': 25, 'banana': 10, 'cherry': 6};
    var key = 'mango';

    if ( map1.containsKey(key) ) {
        print('The key is present in this Map.');
    } else {
        print('The key is not present in this Map.');
    }
}

Output

The key is not present in this Map.

Since the given key is not present in this Map, containsKey() returned false.

Conclusion

In this Dart Tutorial, we learned how to check if the given key is present in this Map, using Map.containsKey() method.