Is there any shorter version for checking both empty and/or null string in Dart?
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.
Comments
-
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 over 3 yearsJust 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 over 3 yearsThank 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 over 3 yearsThank you for the edit and the opinions, I will definitely try to explain it better next time!