Skip to content

FormState validation method to return a Map of the validation status of children FormField(s) #135363

@SharbelOkzan

Description

@SharbelOkzan

Is there an existing issue for this?

Use case

In a screen containing a relatively long Form in a SingleChildScrollView, we want to bring the user's attention to the field that may cause a validation error after calling FormState.validate(). The solution was as follows:

  void _validateForm(BuildContext context) {
    if (_fomKey.currentState!.validate()) {
      fun();
    } else {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (_someWidgetKey.currentContext != null && _someWidgetKey.currentContext!.mounted) {
          Scrollable.ensureVisible(
            _someWidgetKey.currentContext!,
          );
        }
      });
    }
  }

Now the problem is that where there are multiple widgets that may cause a validation error. There's currently no way to detect which one we should scroll to.
The only solution is to implement a custom validation logic, which defies the whole purpose of using Form

Proposal

The proposal is to have another version of the validate method, let's call it, validateGranularly (naming suggestions are very welcome) that returns Map<Key, bool>, so the above problem will be addressed as follows:

  void _validateForm(BuildContext context) {
    if (_fomKey.currentState!.validate()) {
      fun();
    } else {
      Key invalidFieldKey =  
      _fomKey.currentState!.validateGranularly().firstWehere((e) => !e) // e==false
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (invalidFieldKey .currentContext != null && invalidFieldKey .currentContext!.mounted) {
          Scrollable.ensureVisible(
            invalidFieldKey .currentContext!,
          );
        }
      });
    }
  }

Metadata

Metadata

Assignees

Labels

P2Important issues not at the top of the work lista: text inputEntering text in a text field or keyboard related problemsc: new featureNothing broken; request for a new capabilityc: proposalA detailed proposal for a change to Flutterf: material designflutter/packages/flutter/material repository.frameworkflutter/packages/flutter repository. See also f: labels.team-designOwned by Design Languages teamtriaged-designTriaged by Design Languages team

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions