Skip to content

fix: #1484 autoValidateMode breaks invalidate method#1506

Merged
deandreamatias merged 6 commits intoflutter-form-builder-ecosystem:mainfrom
majumdersubhanu:issue-1484
Apr 20, 2026
Merged

fix: #1484 autoValidateMode breaks invalidate method#1506
deandreamatias merged 6 commits intoflutter-form-builder-ecosystem:mainfrom
majumdersubhanu:issue-1484

Conversation

@majumdersubhanu
Copy link
Copy Markdown
Contributor

@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).
⚠️ Report is 7 commits behind head on main.

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!

Comment thread lib/src/form_builder_field.dart
Comment thread lib/src/form_builder_field.dart
@deandreamatias deandreamatias merged commit 38a24f6 into flutter-form-builder-ecosystem:main Apr 20, 2026
7 of 8 checks passed
@majumdersubhanu majumdersubhanu deleted the issue-1484 branch April 22, 2026 09:10
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