Home > Blockchain >  How to do null/empty check of a String inside a TextFormField validator function in dart/flutter?
How to do null/empty check of a String inside a TextFormField validator function in dart/flutter?

Time:09-14

Is there a shorter way to check if a string is either null or empty? Do I need to write every time 2 conditions inside if to check it?

validator: (value) {
    if (value == null || value.isEmpty){
        //....
    }
}

In python we can do if value and it works. In javascript we could do if(!value).

CodePudding user response:

As from my understanding, the TextEditingController use TextEditingValue.empty which is providing empty string initially. I am not able to get null exception.

I think we can use ! while we are sure the value is empty, not null.

validator: (value) {
  if (value!.isEmpty) return "Empty";

I always prefer checking null first, for nullable data type.

CodePudding user response:

try this

validator: (value) {
if (value.isNotEmpty){
     print(value);
 }else{
   print("Empty");
 }
}
  • Related