How to validate fields with Flutter?

Asked

Viewed 124 times

-2

I have a screen that needs to validate 2 fields. If one or both receive wrong values, return me one snackbar with the error message. However, I would like to leave the field in red as soon as I return to snackbar, but I cannot make that return.

TextFormField(
                                // ignore: deprecated_member_use
                                
                                controller: _emailController,
                                decoration: InputDecoration(
                                    prefixIcon: Icon(
                                      Icons.mail_outline,
                                      color: greenColor,
                                    ),
                                    border: OutlineInputBorder(
                                     
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                    labelText: 'E-mail'),
                                
                                validator: (email) {
                                  if (!emailValid(email))
                                    return _errorSnackBar(errorEmail);
                                  return null;
                                },
                              )

Now with just an error message on return the bar completely distorts inserir a descrição da imagem aqui

1 answer

0

Textformfield Validator is not only used to make the bar red, it is smaller because you must inform an error message in the component itself and not show a Snackbar, this is the original behavior.

You return null if the validation passed and returns the error, a String, if it did not pass.

Validator: (String value){ if(value.isEmpty) Return "The field is empty!" ; Else Return null; }

You have two options:

  • Standard mode, show only the error in the component itself by removing the Snackbar.

  • Using external validation, placing your Textformfield inside a Container and giving it a border, dynamically changing the color of this border if you have an error, this is more work because you will practically make the functionality of Textformfield in hand.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.