Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I validate a single form field in flutter

Tags:

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.

like image 411
MarcS82 Avatar asked Feb 12 '20 14:02

MarcS82


1 Answers

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'),
      ),
    ]));
  }
}

like image 80
Spatz Avatar answered Sep 19 '22 23:09

Spatz