How to check a string null in Dart?

Viewed 8222

How do you check a string for "null" in Dart? (not a null object)

is there some Dart SDK API like Java's equals?

4 Answers

I believe isEmpty property will return false since if your string is null, it still holds an object and won't be empty. So depending on what you mean in your post.

If you want to check for the string 'null', just do

if (stringVar == 'null')

or if you want to check if your string is null, then

if (stringVar == null)

Checking if the string is null:

if (s == null) {
    …
}

Checking if the string is not null:

if (s != null) {
    …
}

Returning the string if not null, 'other value' otherwise:

return s ?? 'other value'

Assigning a value to the string only if that string is null:

s ??= 'value'

Calling a method (property) on the string if it's not null

s?.length

You can use the isEmpty property.

bool [string name] isEmpty;

Alternatively, you can do this:

String text = "text"; 
print(text.isEmpty); 

Output: false

Edit: I believe that Mohammad Assad Arshad's answer is more accurate. Sorry about that.

In addition to

myString == 'null'

or

myString == null

There is another meaning that "null" could take: the null character. In ASCII or Unicode this has the code value of 0. So you could check for this value like so:

myString == '\u0000'

or

myString.codeUnits.first == 0
Related