Search code snippets, questions, articles...

Check if a String is empty or null in Dart / Flutter

In this post, we are going to explain how to check if a String is empty or not. We will also cover if the given value is null, false, or 0. If you are using Dart or Flutter to create your application, you can use the code examples listed here.
void checkString(String str) {
  if (str.isEmpty) {
    print('String is empty');
  } else {
    print('String is not empty');
  }
}

void main() {
  checkString('');
  // -> String is empty
  
  checkString('hello');
  // -> String is not empty
}
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

Explanation of the above code example

  1. Created a function checkString that takes the string value as a parameter.
  2. Inside the checkString() function, we are using String.isEmpty and it will print "String is empty" if the string is empty.
  3. Testing the above function for two values '' and 'hello'.

Check if values are null, empty, false using List.contains() function

void checkString(value) {
  if (['', null, 0, false].contains(value)) {
    print('Value is falsey');
  } else {
    print('Value is OK');
  }
}

void main() {
  checkString('');
  // -> Value is falsey
  
  checkString(null);
  // -> Value is falsey
  
  checkString(false);
  // -> Value is falsey
  
  checkString('hello');
  // -> Value is OK
  
  checkString(0);
  // -> Value is falsey
}
Was this helpful?
0 Comments