Home > Blockchain >  flutter how to check if Map is null?
flutter how to check if Map is null?

Time:10-08

map defined as follow:

Map<String,dynamic> allAvailableTime;

the map should be empty when user initialize the page:

I would like to perform null check before getting data from the map however these are not working...

check 1:

allAvailableTime == null ?

error:

type 'String' is not a subtype of type 'Widget'

check 2:

allAvailableTime == {} ?

the check should return True, but it returns False instead ..

check 3:

allAvailableTime.isEmpty ?

error 3:

The getter 'isEmpty' was called on null.
Receiver: null
Tried calling: isEmpty

CodePudding user response:

If you want a null map, you have to do this.

Map<String,dynamic>? allAvailableTime;

CodePudding user response:

To null Check. It should be nullable

void main() {
 
 //1. Making Map Nullable 
 Map<String,dynamic>? allAvailableTime;
 print(allAvailableTime==null);
 //Output: true
  
  
 //2. If you dont want to make it nullable
 Map<String,dynamic> allAvailableTime1 = {};
 print(allAvailableTime1.isEmpty);
  //Output: true
}

Without NullSafety

void main() {
 
 //1. Making Map Nullable 
 Map<String,dynamic> allAvailableTime;
 print(allAvailableTime==null);
 //Output: true
  
  
 //2. If you dont want to make it nullable
 Map<String,dynamic> allAvailableTime1 = {};
 print(allAvailableTime1.isEmpty);
  //Output: true
}

CodePudding user response:

You can check like this

Map<String, dynamic> allAvailableTime;
 if (allAvailableTime?.isEmpty ?? true) {
  // Returns true if there is no key/value pair in the map.
 }
  • Related