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

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

Last updated: March 31, 2023

When working with Flutter and Dart, there might be cases where you have to check whether a given string is null or empty. We can define a reusable function to do the job 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.

Related Articles