Tuesday, December 13, 2022

[FIXED] How to do null/empty check of a String inside a TextFormField validator function in dart/flutter?

Issue

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).


Solution

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.



Answered By - Yeasin Sheikh
Answer Checked By - Marilyn (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.