validate method
Validate all fields of form
Focus to first invalid field when has field invalid, if focusOnInvalid is true.
By default true
Auto scroll to first invalid field focused if autoScrollWhenFocusOnInvalid is true.
By default false.
Note: If a invalid field is from type TextField and will focused,
the form will auto scroll to show this invalid field.
In this case, the automatic scroll happens because is a behavior inside the framework,
not because autoScrollWhenFocusOnInvalid is true.
Implementation
bool validate({
bool focusOnInvalid = true,
bool autoScrollWhenFocusOnInvalid = false,
}) {
_focusOnInvalid = focusOnInvalid;
final hasError = !_formKey.currentState!.validate();
if (hasError) {
final wrongFields = fields.values
.where((element) => element.hasError)
.toList();
if (wrongFields.isNotEmpty) {
if (focusOnInvalid) {
wrongFields.first.focus();
}
if (autoScrollWhenFocusOnInvalid) {
wrongFields.first.ensureScrollableVisibility();
}
}
}
return !hasError;
}