Dart| Flutter How to: Check whether Map is empty or not Example

This tutorial shows different ways to check whether a map is empty or not in Dart or Flutter.

This post talks about the below things.

  • How to check if a given map is null or not and the length is zero
  • Find whether the map is empty or blank.
  • Check map contains no elements

In dart, what is an empty map?

An empty map has no elements and is blank.

You can check another post, How to create an empty map in flutter

Dart Map has built-in properties for checking whether an object is empty or not.

  • length: returns the total number of elements in a Map. If it returns 0 then the map is empty.
  • isEmpty: Checks for an empty map and returns a boolean value, true indicates that the map is empty.
  • isNotEmpty: Checks for a non-empty map and returns a boolean value. false indicates that the map is empty.

How to check whether Map is empty or not in Dart Flutter using the isEmpty property in dart

isEmpty always returns a boolean value true or false. - true: return if the map is empty. - false: return if the map is non-empty.

It is used to check the Map is empty without key and value pairs.

Here is an example program code

void main() {
  Map dictionary = {};
  print(dictionary.isEmpty); //true
  if (dictionary.isEmpty)
    print("map is empty");
  else {
    print("map is not empty");
  }
}

Output:

true
map is empty

Check if the Map is non-empty using the isNonEmpty property in the dart

isNonEmpty always returns the boolean value true or false. - true: return if the map is non-empty. - false: return if the map is empty.

It checks a map for non-empty and returns true and false Here is an example code

  Map dictionary = {};
  print(dictionary.isNotEmpty); //true
  if (dictionary.isNotEmpty)
    print("map is not empty");
  else {
    print("map is empty");
  }
}

Output:

false
map is empty

How to Check an empty map using the length property in the flutter

The ‘length’ property always returns an ‘int’ value. If it is ‘zero,’ the map is empty.

Otherwise, the map is not empty.

It, like the other approaches mentioned above, does not return a boolean value.

It is used in conditional statements such as ‘if’, and the result must be compared to zero again, i.e. (map.length==0).

This approach is recommended to use the size of a Map object.

Here’s an example of a code

void main() {
  Map dictionary = {};
  print(dictionary.length); //0
  if (dictionary.length == 0)
    print("map is empty");
  else {
    print("map is not empty");
  }
}

Output:

0
map is empty

Conclusion

Learned multiple approaches to finding an empty map or not in dart and flutter.