Dart: Checking whether a Map is empty

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

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.

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:

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.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like