Reputation: 961
How do you check a string for "null" in Dart? (not a null
object)
is there some Dart SDK API like Java's equals
?
Upvotes: 4
Views: 11544
Reputation: 135
Most of the time the application does not work especially when you are using Future<String>
return type
the below code seems to work
myString == "null";
myFinalString = ["", null, "null", "\"null\""].contains(myString);
print(myFinalString)
Output:
=>true
Upvotes: -1
Reputation: 512824
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
Upvotes: 1
Reputation: 33511
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
Upvotes: 4
Reputation: 312
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.
Upvotes: 1
Reputation: 1784
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)
Upvotes: 7