MarcS82
MarcS82

Reputation: 2517

how can I validate a single form field in flutter

I have a form with multiple controls but spreaded over mulitple tabs. If the user clicks a button I like to call the validator function for a single field.

Upvotes: 20

Views: 10993

Answers (1)

Spatz
Spatz

Reputation: 20118

To validate individual form field create key with FormFieldState type, assign that key to form field and call validate method on key's current state:

class MyCustomForm extends StatefulWidget {
  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}

class MyCustomFormState extends State<MyCustomForm> {
  final _formFieldKey = GlobalKey<FormFieldState>();

  @override
  Widget build(BuildContext context) {
    return Form(
        child: Column(children: <Widget>[
      TextFormField(
        key: _formFieldKey,
        validator: (value) {
          if (value.isEmpty) {
            return 'Please enter some text';
          }
          return null;
        },
      ),
      TextFormField(
        validator: (value) {
          if (value.isEmpty) {
            return 'Please enter some text';
          }
          return null;
        },
      ),
      RaisedButton(
        onPressed: () {
          if (_formFieldKey.currentState.validate()) {
            Scaffold.of(context)
                .showSnackBar(SnackBar(content: Text('Processing Data')));
          }
        },
        child: Text('Submit'),
      ),
    ]));
  }
}

Upvotes: 49

Related Questions