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

Updated: July 10, 2022 By: A Goodman Post a comment

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

Example:

// kindacode.com
// create a sample map
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

Related Articles