Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Form get validity of all form fields without error reporting

Basically, I am looking for FormFieldState.isValid but for FormState.

So the challenge is that I want to enable/disable my form submit button on the fly depending on whether all the form fields are valid, without calling FormState.validate() until the submit button is actually clicked because that will report errors for the yet invalid fields.

like image 332
nwagu Avatar asked Dec 10 '25 06:12

nwagu


2 Answers

im keeping an extra variable around for isValid and storing it in a stream so everytime a field changes we ask if its valid and notify our isValid variable, its possible this might become out of sync with the form at some point so isnt ideal but it kind of works

like image 139
martinseal1987 Avatar answered Dec 11 '25 21:12

martinseal1987


From docs:

bool validate() - Calls FormField.validator to set the errorText. Returns true if there were no errors.

So if we want to validate without setting the errorText we should use FormField.validator directly.

This is exactly what isValid property does!

bool isValid - True if the current value is valid. This will not set errorText or hasError and it will not update error display.

Looping button logic to one-time check of isValid inside a build() method will not update the button. The way I can think of is a setState() on every text change. The easiest way to detect all changes is probably subscribe to all TextEditingControllers.

bool allFormsAreValid = false;

void revalidate() {
  final allValid = [formStateA, formStateB, ...].all((f) => f.isValid);
  if (allValid != allFormsAreValid) {
    setState(() => allFormsAreValid = allValid);
  }
}

void initState() {
  myControllerA.listen(revalidate);
  myControllerB.listen(revalidate);
  ...
}

// use allFormsAreValid inside `build`

IMHO not showing error messages and not showing the button is a strange user experience. It was never intended this way and code will look ugly.

like image 27
Alexey Bukin Avatar answered Dec 11 '25 22:12

Alexey Bukin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!