Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flutter how to check if Map is null?

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
like image 770
icantcode Avatar asked Oct 23 '25 19:10

icantcode


2 Answers

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
}

like image 74
Yaseen Avatar answered Oct 26 '25 09:10

Yaseen


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

Map<String,dynamic>? allAvailableTime;
like image 37
lsaudon Avatar answered Oct 26 '25 10:10

lsaudon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!