{

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


This tutorial explains about 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, 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, 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 for 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
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart Example - Program to check Leap year or not

Dart/Flutter How to Check string contains alphabetic number

Dart| Flutter How to check element exists in Array

Dart| Flutter How to: Convert Map to Query String with example

Dart| Flutter How to: Multiple ways to get the First and last letter of a string

Dart| Flutter: How to Convert timestamp epoch to DateTime local and UTC| Flutter By Example

Dart| Flutter: How to Convert timestamp string from 24 hours to 12 hour format| Flutter By Example