How to check if a string is empty in Dart
The isEmpty property checks if the string is empty. The isNotEmpty property, on the other hand, checks if the string is not empty.
Syntax
string.isNotEmpty
string.isEmpty
Return value
-
The
isNotEmptyproperty returnstrueif the string is not empty. Otherwise,falseis returned. -
The
isEmptyproperty returnstrueif the string is empty. Otherwise,falseis returned.
Code
The code below demonstrates how to check whether or not the string is empty.
void main() {// create a empty stringvar str = "";print('The string is - $str.');// check if the string is not emptyprint("str.isNotEmpty : ${str.isNotEmpty}");// check if the string is emptyprint("str.isEmpty : ${str.isEmpty}");str = "hi";print('\nThe string is - $str.');// check if the string is not emptyprint("str.isNotEmpty : ${str.isNotEmpty}");// check if the string is emptyprint("str.isEmpty : ${str.isEmpty}");}
Code explanation
-
Line 3: We create a variable named
strand assign an empty string as a value. -
Line 7: We use the
isNotEmptyproperty to check ifstris not empty. In our case,stris empty, sofalseis returned. -
Line 10: We use the
isEmptyproperty to check ifstris empty. In our case, thestris empty, sotrueis returned. -
Line 12: We change the value of the
strvariable to the"hi"string. -
Line 15: We use the
isNotEmptyproperty to check ifstris not empty. In our case,stris not empty, sotrueis returned. -
Line 17: We use the
isEmptyproperty to check ifstris empty. In our case, thestris not empty, sofalseis returned.