Skip to content

subscribeToFields used with setAutovalidate causes immediate validation #29

@gogolon

Description

@gogolon

Even with autovalidate set to true on a form, validation should only happen after a field's value is set. If subscribeToFields is used, the validation should only happen after the field that was subscribed to is set. Currently, validation is triggered immediately, which leads to validation errors being emitted instantly after setAutovalidate(true) call. The test below should pass because setValue is never called on fieldA.

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

per my understanding, the cause of this is as follows:
setAutovalidate(true) causes the registered fields to emit a state. subscribeToFields sets up a listener which is triggered by this new state (the field's value did not change, but the listener thinks it did because it did not register the initial value) , and the listener triggers validation of the field.

The issue can be worked around by postponing subscribeToField so that the listener is not triggered by the state emission caused by setAutovalidate(true):
Future.microtask(() => fieldB.subscribeToFields([fieldA]));

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions