The secret to async validation on Flutter forms

The Situation

The Secret

  1. First setup a local boolean that maintains the success/failure of the result of the async call. Then add this to the sync validator to generate an async validation message that describes the failure case (like ‘Invalid Username’).
  2. After submitting a form and passing the sync validator make an async call (like to a backend). After returning from the async call, set the local boolean with the success/failure of the result of the async call and call SetState(). This will redraw the form…. But it will not re-rerun the async validator!
    There is a solution for that too!
  3. Place a call to explicitly re-run the async validator at the start of the build() method. This will re-run the async validator before the form is rebuilt. After the form completes rebuilding, the async validator results are displayed (if any) on the form just like you would expect.

Let’s see it!

  1. The user first enters a username and password that triggers the sync validator and displays an error message (must be 8 characters). This is the normal use of a form validator.
  2. The user then enters a username and password that passes the sync validator. This is where the secret sauce kicks in. Once the sync validator passes, a call is made to the backend. The result from the backend indicates the username/password combination are incorrect, so the async validator is triggered and displays an error message(incorrect user/pass).
  3. The user then enters the correct user/pass combination. This initiates another call to the backend. This time the user/pass is correct and no validators (sync or async) are triggered. The user is then logged in.

Show me how




Software Dev @nocnoc Big Flutter Fan

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store