18.7 C
New York
Tuesday, September 27, 2022

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

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.Advertisements

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:Advertisements

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.

Advertisements

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles