OneBite.Dev - Coding blog in a bite size

Check If A String Is Empty In Dart

Code snippet for how to Check If A String Is Empty In Dart with sample and detail explanation

In Dart programming, checking if a string is empty or null is an important practice to avoid null exceptions or undesired output. This simple article is designed to provide a quick guide on how to check if a string is empty or null in Dart.

Code snippet for Checking if a String is Empty in Dart

Here is a simple code snippet for checking string emptiness:

void main() {
  String str = "";
  
  if (str.isEmpty) {
    print('The string is empty');
  } else {
    print('The string is not empty');
  }
}

You can also check if a string is null or empty at the same time in Dart like this:

void main() {
  String str;
  
  if (str == null || str.isEmpty) {
    print('The string is null or empty');
  } else {
    print('The string is not null or empty');
  }
}

Code Explanation for Checking if a String is Empty in Dart

In the first code snippet, we declare a string variable ‘str’ and assign it an empty value. The ‘if’ condition str.isEmpty checks whether the string is empty or not. The isEmpty property in Dart checks whether the string is an empty string(i.e., its length is zero). If the condition is true, it prints ‘The string is empty’. If not, it prints ‘The string is not empty’.

In the second code snippet, the ‘str’ variable is not assigned a value, so it is directly checked for null or empty. The ‘if’ statement str == null || str.isEmpty checks whether the string is null or empty. If the string is either null or empty, it prints ‘The string is null or empty’. If not, it prints ‘The string is not null or empty’.

These simple codes will help you avoid complications in your Dart programming related to empty or null strings. Always remember that taking this precaution can greatly reduce the occurrence of unexpected errors.

dart