Skip to content

validateAll used with setAutovalidate causes immediate validation #30

@gogolon

Description

@gogolon

Setting validateAll in a FormGroupCubit while also using setAutovalidate(true) causes immediate validation of the form. The validation should not happen until any of the fields is changed. The below test should pass, but it does not.

    test(
        'validateAll does not cause immediate validation when used along setAutovalidate(true)',
        () async {
      final fieldA = TextFieldCubit<bool>(validator: (_) => false);
      FormGroupCubit(validateAll: true)
        ..registerFields([fieldA])
        ..setAutovalidate(true);
      await Future<void>.delayed(Duration.zero);
      expect(fieldA.state.isValid, true);
    });

per my understanding, the cause is as follows:

  1. in registerFields a value is added to the _fieldController:
// inform that the fields have changed
_fieldsController.add(null);
  1. setAutovalidate(true) is called synchronously after registerFields
  2. in the following event loop cycle, _onFieldsStateChanged listener is triggered by the item added in 1). Because validateAll is set to true and we called setAutovalidate, validation is triggered.

The issue can be worked around by postponing setValidate(true) until the listener's callback is executed:
Future.microtask(() => setValidate(true));

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions