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 isNotEmpty property returns true if the string is not empty. Otherwise, false is returned.

  • The isEmpty property returns true if the string is empty. Otherwise, false is returned.

Code

The code below demonstrates how to check whether or not the string is empty.

void main() {
// create a empty string
var str = "";
print('The string is - $str.');
// check if the string is not empty
print("str.isNotEmpty : ${str.isNotEmpty}");
// check if the string is empty
print("str.isEmpty : ${str.isEmpty}");
str = "hi";
print('\nThe string is - $str.');
// check if the string is not empty
print("str.isNotEmpty : ${str.isNotEmpty}");
// check if the string is empty
print("str.isEmpty : ${str.isEmpty}");
}

Code explanation

  • Line 3: We create a variable named str and assign an empty string as a value.

  • Line 7: We use the isNotEmpty property to check if str is not empty. In our case, str is empty, so false is returned.

  • Line 10: We use the isEmpty property to check if str is empty. In our case, the str is empty, so true is returned.

  • Line 12: We change the value of the str variable to the "hi" string.

  • Line 15: We use the isNotEmpty property to check if str is not empty. In our case, str is not empty, so true is returned.

  • Line 17: We use the isEmpty property to check if str is empty. In our case, the str is not empty, so false is returned.

Free Resources