Dart/Flutter: How to check if Map is null or not

This tutorial explains checking if the given map is null or not in dart and flutter programming null map in dart means if a variable is declared of Map type without initialized with the operator.

For example, Let’s see an example of a Map being declared but not initialized with the operator.

Map<int, String>? employees;
  or
Map<int, String>? employees=null;

employees variable is declared, but not initialized.

Another example is, the map is declared with empty values literal syntax.

  Map<int, String>? employees={};

How to check if the given map is null or empty

In this below, the map is declared and not assigned with value, So Map always returns null

void main() {
  Map<int, String>? employees;
  print(employees); // null
  print(employees==null); // true

}

Here is an empty map declared assigned with empty data using literal syntax.

You can use the isEmpty property that returns true if the map is empty.

void main() {
  Map<int, String>? employees={};
 print(employees); // {}
  print(employees==null); // false
  print(employees.isEmpty); // true

}

Empty and null checks validations are checked before accessing map elements. This can be done with conditional statements such as if else.

Here is an example of Check Map is empty or null

 void main() {
  Map<int, String>? employees={};
if((employees==null)||(employees.isEmpty)){
   print("Map is empty or null");

}else{
  print("Map is not empty");
}
}

Output:

Map is empty or null