Skip to content

fix: #1484 autoValidateMode breaks invalidate method#1506

Open
majumdersubhanu wants to merge 6 commits intoflutter-form-builder-ecosystem:mainfrom
majumdersubhanu:issue-1484
Open

fix: #1484 autoValidateMode breaks invalidate method#1506
majumdersubhanu wants to merge 6 commits intoflutter-form-builder-ecosystem:mainfrom
majumdersubhanu:issue-1484

Conversation

@majumdersubhanu
Copy link
Copy Markdown

@majumdersubhanu majumdersubhanu commented Apr 14, 2026

Connection with issue(s)

Close #1484
Close #1485

Solution description

Fixes an issue where invalidate() calls were being cleared by framework validation when autovalidateMode was active. It also introduces support for the new Flutter forceErrorText property across the core library.

Key Changes:

  1. FormBuilderFieldState Persistence Logic:
    • Changed the default value of clearCustomError in validate() from true to false. This prevents framework-triggered validation calls (which pass no arguments) from clearing manual errors.
    • Updated didChange() to explicitly clear _customErrorText. This ensures that manual errors are removed as soon as the user interacts with the field, maintaining a logical UX.
  2. forceErrorText Integration:
    • Added forceErrorText to FormBuilderField, FormBuilderFieldDecoration, and core field constructors.
    • This aligns the library with Flutter's updated FormField API (introduced in v3.24), allowing for declarative external error management.
  3. Enhanced Documentation:
    • Updated docstrings for validate() and invalidate() to reflect the updated behavior regarding custom error clearing.
Code used for the demo
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';

void main() {
  runApp(const MaterialApp(home: SignupForm()));
}

class SignupForm extends StatefulWidget {
  const SignupForm({super.key});

  @override
  State<SignupForm> createState() => _SignupFormState();
}

class _SignupFormState extends State<SignupForm> {
  final _formKey = GlobalKey<FormBuilderState>();
  final _emailFieldKey = GlobalKey<FormBuilderFieldState>();
  AutovalidateMode autovalidateMode = AutovalidateMode.disabled;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Signup Form')),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: FormBuilder(
          key: _formKey,
          autovalidateMode: autovalidateMode,
          child: Column(
            children: [
              FormBuilderTextField(
                name: 'full_name',
                decoration: const InputDecoration(labelText: 'Full Name'),
                validator: FormBuilderValidators.compose([
                  FormBuilderValidators.required(),
                ]),
              ),
              const SizedBox(height: 10),
              FormBuilderTextField(
                key: _emailFieldKey,
                name: 'email',
                decoration: const InputDecoration(labelText: 'Email'),
                validator: FormBuilderValidators.compose([
                  FormBuilderValidators.required(),
                  FormBuilderValidators.email(),
                ]),
              ),
              const SizedBox(height: 10),
              FormBuilderTextField(
                name: 'password',
                decoration: const InputDecoration(labelText: 'Password'),
                obscureText: true,
                validator: FormBuilderValidators.compose([
                  FormBuilderValidators.required(),
                  FormBuilderValidators.minLength(6),
                ]),
              ),
              const SizedBox(height: 10),
              FormBuilderTextField(
                name: 'confirm_password',
                autovalidateMode: AutovalidateMode.onUserInteraction,
                decoration: InputDecoration(
                  labelText: 'Confirm Password',
                  suffixIcon: (_formKey.currentState?.fields['confirm_password']?.hasError ?? false)
                      ? const Icon(Icons.error, color: Colors.red)
                      : const Icon(Icons.check, color: Colors.green),
                ),
                obscureText: true,
                validator: (value) => _formKey.currentState?.fields['password']?.value != value ? 'No coinciden' : null,
              ),
              const SizedBox(height: 10),
              FormBuilderFieldDecoration<bool>(
                name: 'test',
                validator: FormBuilderValidators.compose([
                  FormBuilderValidators.required(),
                  FormBuilderValidators.equal(true),
                ]),
                // initialValue: true,
                decoration: const InputDecoration(labelText: 'Accept Terms?'),
                builder: (FormFieldState<bool?> field) {
                  return InputDecorator(
                    decoration: InputDecoration(
                      errorText: field.errorText,
                    ),
                    child: SwitchListTile(
                      title: const Text('I have read and accept the terms of service.'),
                      onChanged: field.didChange,
                      value: field.value ?? false,
                    ),
                  );
                },
              ),
              const SizedBox(height: 10),
              ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState?.saveAndValidate() ?? false) {
                    if (true) {
                      // Either invalidate using Form Key
                      _formKey.currentState?.fields['email']?.invalidate('Email already taken.');
                      // OR invalidate using Field Key
                      // _emailFieldKey.currentState?.invalidate('Email already taken.');
                    }
                  } else {
                    setState(() {
                      autovalidateMode = AutovalidateMode.onUserInteraction;
                    });
                    debugPrint(_formKey.currentState?.value.toString());
                  }
                },
                child: const Text('Signup'),
              )
            ],
          ),
        ),
      ),
    );
  }
}

Screenshots or Videos

Screen.Recording.2026-04-15.004656.mp4

To Do

  • Read contributing guide
  • Check the original issue to confirm it is fully satisfied
  • Add solution description to help guide reviewers
  • Add unit test to verify new or fixed behaviour
  • If apply, add documentation to code properties and package readme

@codecov
Copy link
Copy Markdown

codecov bot commented Apr 14, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.85%. Comparing base (bff073a) to head (d223f21).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1506      +/-   ##
==========================================
- Coverage   91.06%   90.85%   -0.22%     
==========================================
  Files          21       21              
  Lines         851      853       +2     
==========================================
  Hits          775      775              
- Misses         76       78       +2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Copy Markdown
Collaborator

@deandreamatias deandreamatias left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On issue related, had this steps to reproduce, but I can't see this flow in your video

tap Signup button once to set autovalidateMode = onUserInteraction.
and then fill the form
tap signup button again.

Please can create a video following this steps? Thanks!

@override
bool validate({
bool clearCustomError = true,
bool clearCustomError = false,
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a breaking change. Need to add some advice for developers that use this method.
Maybe implement some dart fix (https://github.com/flutter-form-builder-ecosystem/flutter_form_builder/blob/main/lib/fix_data.yaml)

Copy link
Copy Markdown
Author

@majumdersubhanu majumdersubhanu Apr 14, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@deandreamatias I've updated the video to do the exact steps to reproduce, please have a look, I'll add the dart fix ASAP.

/// In previous versions, calling `validate()` would automatically clear any custom errors set via `invalidate()`.
/// Now, `validate()` does not clear custom errors by default.
/// If you want to clear the custom error when validating, you must explicitly pass `clearCustomError: true`.
///
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@deandreamatias I've added the breaking change notice to Dartdoc. I don't think implementing a dart fix will work here since data-driven fixes in Dart are only triggered when static analysis finds an issue such as a compilation error or deprecated usage.

  • validate must exist, as it is an overridden method from Flutter's FormFieldState.
  • We cannot deprecate it (which would trigger the analyzer).
  • The change merely involves passing an optional named parameter (clearCustomError: false), which is a valid syntax.

Since there's no compiler warning or error generated on existing, valid validate() calls, the static analysis tool won't flag anything and, ultimately, bypasses the file when a developer runs dart fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FormBuilderFiled: Support forceErrorText [FormBuilder]: AutovalidateMode Always and onUserInteraction break invalidate method

2 participants