22.1 C
New York
Friday, August 19, 2022

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

- Advertisement -

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:Advertisements

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:

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

Advertisements
- Advertisement -

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles