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

1,273

Solution 1

You can write an extension for this

void main() {
  String str;
  print(str.isNotNullAndNotEmpty);
}

extension on String {
  bool get isNotNullAndNotEmpty => this != null && this.isNotEmpty;
}

Solution 2

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.

Share:
1,273
Zenko
Author by

Zenko

Creating apps for a living and for fun!

Updated on December 20, 2022

Comments

  • Zenko
    Zenko over 1 year

    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.

  • iDecode
    iDecode over 3 years
    Just because your shorter version looks short doesn't necessary means it is easier to understand, I suspect future readers would need to spend more time on shorter version than the longer.
  • Zenko
    Zenko over 3 years
    Thank you for the answer. This also works. Thats why I also upvote it but it is hard to read. The extension method is a better solution for readability.
  • ShachinRamkumar
    ShachinRamkumar over 3 years
    Thank you for the edit and the opinions, I will definitely try to explain it better next time!