How to use the containsKey() method in Dart

Overview

The containsKey() method in Dart checks if an entry for the specified key is present in SplayTreeMap.

Syntax

bool containsKey(Object? key)

Argument: This is the key to be searched and passed as an argument.

Return value

This method returns true if there is an entry for the provided key. Otherwise, it returns false.

Code

The code below demonstrates how to use containsKey() to check if there is an entry present for the specified key:

import 'dart:collection';
void main() {
//Create a new SplayTreeMap that can have the int key and string values
SplayTreeMap map = new SplayTreeMap<int, String>((keya,keyb) => keyb.compareTo(keya));
// Add five entries to the map
map[5] = "Five";
map[4] = "Four";
map[2] = "Two";
map[1] = "One";
map[3] = "Three";
print('The map is $map');
print('map.containsKey(5) : ${map.containsKey(5)}');
print('map.containsKey(10) : ${map.containsKey(10)}');
}

Code explanation

Line 1: We import the collection library.

Line 4: We create a new SplayTreeMap object named map. We pass a compare function as an argument. This function maintains the order of the map entries. In our case, the compare function orders the elements in descending order.

Lines 7 to 11: We add five new entries to the map. Now, the map is _{5=Five,4=Four,3=Three,2=Two,1=One}_.

Line 15: We use the containsKey() method to check if the map contains an entry for the key 5. The map has an entry for the key 5, so the methods returns true.

Line 16: We use the containsKey() method to check if the map contains an entry for the key 10. The map doesn’t have an entry for the key 10, so the method returns false.

Free Resources