Dart: Checking if a Map contains a given Key/Value

Last updated on August 17, 2021 A Goodman Loading... Post a comment

Dart provides us the tools to quickly check whether a map contains a given key or value. These tools are the containsKey() method and containsValue() method.

Example:

// main.dart
Map<String, dynamic> item = {
  'id': 123,
  'name': 'A Useless Pink Phone',
  'OS': 'Android',
  'manufacturer': 'KindaCode.com',
  'price': 0.1,
  'freeship': true
};

void main() {
  if (item.containsKey('weight')) {
    print('The weight of the product is ${item['weight']}');
  } else {
    print('No weight provided');
  }

  if (item.containsValue('Kindacode.com')) {
    print('The product is bad. You should not buy it');
  } else {
    print('The product is not from Kindacode.com');
  }
}

Output:

No weight provided
The product is not from Kindacode.com

Further reading:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like