Skip to content

[Feature Request] Add BuildContext to FormFieldValidator function #59059

@matanshukry

Description

@matanshukry

Suggestion

I'm suggesting adding a BuildContext argument to the FormFieldValidator function. From what I can tell it's called in a place where the context exist, so it shouldn't be much of a problem

Use Case/Reason

I've created a specialized type of FormField, GenderFormField, much like the TextFormField.

In it, I'm also providing a default validation, verifying a non-null result (it depends on the arguments provided in the constructor, but still).

If that is true, I'm providing a function to the validator argument in the form of a static function. Since it's static I can't access the context nor a locale, so I can't return locale-specific error strings.

Example code:

  GenderFormField({
    Key key,
    this.controller,
    Gender initialValue,
    bool enabled,
    FormFieldSetter<Gender> onSaved,
    bool autovalidate = false,
  }) : super(
          key: key,
          initialValue: controller != null ? controller.value : initialValue,
          onSaved: onSaved,
          autovalidate: autovalidate,
          enabled: enabled ?? true,
          validator: _defaultValidator,
          builder: (state) {
...
...

The default validator is a simple one, but currently it return constant strings rather than using the context and getting the locale and getting locale-specific strings.

Current Solution

Currently as a solution I've created a static function to return the default validator,
and everywhere where I'm using the form field I'm calling it with
validator: GenderFormField.createDefaultValidator(context),

  static FormFieldValidator<Gender> createDefaultValidator(BuildContext context) {
    final locale = MyLocale.of(context);

    return (Gender value) {
      .. impl ...
    };
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3Issues that are less important to the Flutter projectc: new featureNothing broken; request for a new capabilityframeworkflutter/packages/flutter repository. See also f: labels.good first issueRelatively approachable for first-time contributorsteam-frameworkOwned by Framework teamtriaged-frameworkTriaged by Framework teamworkaround availableThere is a workaround available to overcome the issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions