how to Check if string is empty in dart
how to Check if string is empty in dart

Hi Guy’s Welcome to Proto Coders Point, In this Flutter dart article let’s learn how to validate a String Variable to check if the given String is empty or null.

Suppose, You are building an application where you ask user to enter some data & you don’t accept empty or null value.

At situation, we need to check if string is empty or null, Let’s Start:

Function to check of String is null or empty

Will create a function/method that will validate our string, Let’s name the function as stringValidator()

bool stringvalidator(String? value) {
  if (value == null) {
    return false;
  }

  if (value.isEmpty) {
    return false;
  }

  return true;
}

Let’s make the above function shorter by using ternary operation in dart.

bool stringvalidator(String? value) {
   return value?.isNotEmpty ?? false;
}

The above function, return true if String variable contain atleast one character, else return false if string is empty or null.

Complete Code – To check if string variable is empty or null in dart Flutter

bool stringvalidator(String? value) {
   return value?.isNotEmpty ?? false;
}

void main() {
  print(stringvalidator(''));   // false
  print(stringvalidator('Rajat Palankar'));    // true
  print(stringvalidator(null));   // false
}