Menu
Coddy logo textTech

Checking if a Key Exists

Part of the Fundamentals section of Coddy's Dart journey — lesson 63 of 94.

The containsKey() method checks if a map contains a specific key and returns a boolean result. This helps you verify if a key exists before trying to access its value.

Create a map of student scores:

Map<String, int> scores = {
  'Alice': 95,
  'Bob': 85,
  'Charlie': 90
};

Check if a key exists in the map:

bool hasAlice = scores.containsKey('Alice');
print('Map contains Alice: $hasAlice');

After executing the above code, the output will be:

Map contains Alice: true

Check for a key that doesn't exist:

bool hasDavid = scores.containsKey('David');
print('Map contains David: $hasDavid');

After executing the above code, the output will be:

Map contains David: false
challenge icon

Challenge

Beginner

In this challenge, you'll practice checking if a key exists in a Map using the containsKey method. This method returns true if the map contains the specified key, and false otherwise.

Complete the code to check if the userInfo map contains the key 'email'. If it does, set the message variable to 'Email found!'; otherwise, set it to 'Email not found!'.

Expected output:

Email found!

Cheat sheet

The containsKey() method checks if a map contains a specific key and returns a boolean result:

Map<String, int> scores = {
  'Alice': 95,
  'Bob': 85,
  'Charlie': 90
};

bool hasAlice = scores.containsKey('Alice');
print('Map contains Alice: $hasAlice'); // true

bool hasDavid = scores.containsKey('David');
print('Map contains David: $hasDavid'); // false

Try it yourself

void main() {
  // This map is already defined for you
  Map<String, String> userInfo = {
    'name': 'John',
    'email': 'john@example.com',
    'address': '123 Main St'
  };
  
  // TODO: Check if the userInfo map contains the key 'email'
  // If it does, set message to 'Email found!'
  // Otherwise, set message to 'Email not found!'
  String message = '';
  
  // This will display the result
  print(message);
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals