Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any shorter version for checking both empty and/or null string in Dart? [duplicate]

I saw many similar questions but I haven't found one which satisfy the question I'm asking now. So suppose I have 3 maps like these:

final map1 = {name: Bill, age: 34, nickname: ''};
final map2 = {name: John, age: 50};
final map3 = {name: Dan, age: 21, nickname: 'Avengers'};

I want to be able to check whether nickname is null or empty so I check like this:

if(map[nickname] != null && map[nickname] != '')

Or

if(map[nickname] == null || map[nickname] == '')

I had to use two conditional checks every time.

Is there a way in Dart so we can shorten this into one condition check?

Thanks and I apologize if this is a duplicate of some other question but I have searched a a bunch of similar questions without finding anything exactly for Dart yet.

like image 518
Zenko Avatar asked Jan 26 '26 23:01

Zenko


1 Answers

if (['', null].contains(map[nickname]))

is the shorter version of

if(map[nickname] == null || map[nickname] == '')

This method uses the contains method of the List class, which returns true if the collection contains an element equal to the input. So if your input String is either null or empty, it returns true.

like image 164
ShachinRamkumar Avatar answered Jan 28 '26 16:01

ShachinRamkumar



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!