29.6 C
New York
Sunday, August 7, 2022

Dart: Checking whether a Map is empty

- Advertisement -

In Dart, you can check if a given map is empty in several ways. The most convenient approaches are to using the isEmpty, isNotEmpty, or length properties.Advertisements

Example:

// main.dart
Map<String, dynamic> map1 = {'website': 'Kindacode.com', 'age': 5};
Map map2 = {};
Map map3 = {'key1': 'Value 1', 'key2': 'Value 2'};

void main() {
  // Using isEmpty
  if (map1.isEmpty) {
    print('Map1 is empty');
  } else {
    print('Map1 is not empty');
  }

  // Using isNotEmpty
  if (map2.isNotEmpty) {
    print('Map2 is not empty');
  } else {
    print('Map2 is empty');
  }

  // Clear map3's entries
  map3.clear();
  // Using length property
  if (map3.length == 0) {
    print('Map3 is empty');
  } else {
    print('Map 3 is not empty');
  }
}

Output:Advertisements

Map1 is not empty
Map2 is empty
Map3 is empty

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
- Advertisement -

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles