Kinda Code
Home/Dart/Dart: Checking whether a Map is empty

Dart: Checking whether a Map is empty

Last updated: August 19, 2022

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

Example:

// main.dart
Map<String, dynamic> map1 = {'website': 'Kindacode.com', 'age': 6};
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 because it was cleared with the clear() method');
  } else {
    print('Map 3 is not empty');
  }
}

Output:

Map1 is not empty
Map2 is empty
Map3 is empty because it was cleared with the clear() method

We’ve traversed an example that demonstrates more than one way to determine if a given map is empty or not. Keep going and learning by taking a look at the following articles:

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

Related Articles