diff --git a/lib/src/form_builder.dart b/lib/src/form_builder.dart index 9ddf88ae0..5a2701cd2 100644 --- a/lib/src/form_builder.dart +++ b/lib/src/form_builder.dart @@ -1,5 +1,4 @@ import 'package:flutter/widgets.dart'; -import 'package:flutter_form_builder/src/extensions/autovalidatemode_extension.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; /// A container for form fields. @@ -107,6 +106,12 @@ class FormBuilderState extends State { final Map _savedValue = {}; // Because dart type system will not accept ValueTransformer final Map _transformers = {}; + bool _focusOnInvalid = true; + + /// Will be true if will focus on invalid field when validate + /// + /// Only used to internal logic + bool get focusOnInvalid => _focusOnInvalid; bool get enabled => widget.enabled; @@ -161,9 +166,6 @@ class FormBuilderState extends State { void setInternalFieldValue(String name, T? value) { _instantValue[name] = value; - if (widget.autovalidateMode?.isEnable ?? false) { - validate(); - } widget.onChanged?.call(); } @@ -253,6 +255,7 @@ class FormBuilderState extends State { bool focusOnInvalid = true, bool autoScrollWhenFocusOnInvalid = false, }) { + _focusOnInvalid = focusOnInvalid; final hasError = !_formKey.currentState!.validate(); if (hasError) { final wrongFields = diff --git a/lib/src/form_builder_field.dart b/lib/src/form_builder_field.dart index 4b2987b63..03827a8c0 100644 --- a/lib/src/form_builder_field.dart +++ b/lib/src/form_builder_field.dart @@ -101,9 +101,6 @@ class FormBuilderFieldState, T> bool get enabled => widget.enabled && (_formBuilderState?.enabled ?? true); bool get readOnly => !(_formBuilderState?.widget.skipDisabled ?? false); - bool get _isEnableValidate => - widget.autovalidateMode.isEnable || - (_formBuilderState?.widget.autovalidateMode?.isEnable ?? false); bool get _isAlwaysValidate => widget.autovalidateMode.isAlways || (_formBuilderState?.widget.autovalidateMode?.isAlways ?? false); @@ -178,7 +175,6 @@ class FormBuilderFieldState, T> _dirty = true; if (enabled || readOnly) { _formBuilderState!.setInternalFieldValue(widget.name, value); - if (_isEnableValidate) validate(); return; } _formBuilderState!.removeInternalFieldValue(widget.name); @@ -243,7 +239,14 @@ class FormBuilderFieldState, T> } final isValid = super.validate() && !hasError; - if (!isValid && focusOnInvalid && enabled) { + final fields = _formBuilderState?.fields ?? + , dynamic>>{}; + + if (!isValid && + focusOnInvalid && + (formState?.focusOnInvalid ?? true) && + enabled && + !fields.values.any((e) => e.effectiveFocusNode.hasFocus)) { focus(); if (autoScrollWhenFocusOnInvalid) ensureScrollableVisibility(); }