Flutter & Dart: How to Check if a String is Null/Empty

Last updated on May 11, 2022 The Plumber Loading... Post a comment

When working with Flutter and Dart, there might be cases where you have to check whether a given string is null or empty. Suppose that our app’s functionality only continues when the string is neither null nor empty then we would create a reusable function named validateString as follows:

bool validateInput(String? input) {
  if (input == null) {
    return false;
  }

  if (input.isEmpty) {
    return false;
  }

  return true;
}

We can shorten the function like this:

bool validateInput(String? input) {
  return input?.isNotEmpty ?? false;
}

The function will return false if the input is null or empty. It will return true if this string contains at least one character. Let’s give it a shot:

// main.dart
bool validateInput(String? input) {
  return input?.isNotEmpty ?? false;
}

void main() {
  print(validateInput(''));
  print(validateInput('abc'));
  print(validateInput(null));
}

Output:

false
true
false

That’s it. Further reading:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like