You will want to wrap your entire form with a Form
widget.
You can then pass a GlobalKey<FormState>
into the Form
to get a reference to it that you can use in other methods
You should create your form key in the initState()
of your State
class (make sure you are using a StatefulWidget
).
Once you have done this, you can pass a validator
to your TextFormField
s. The validator
takes a string, and returns null
if the input is valid, or an error message string if the input is invalid.
Then, on the submit button, you can call formKey.currentState.validate()
. This method returns false
if any text field failed its validator.
For example:
GlobalKey<FormState> _formKey;
@override
void initState() {
super.initState();
_formKey = GlobalKey();
}
@override
Widget build(BuildContext context) {
return Form(key: _formKey, child: Column(
children: [
TextFormField(
validator: (value) {
if (value.isEmpty) return 'Please enter a value';
else return null;
},
controller: ... // whatever controller you are using
),
FlatButton(
child: Text('Submit'),
onPressed: () {
if (_formKey.currentState.validate()) {
// if this returns true, all the text fields have got good data (i.e. all fields are non-empty)
doSomething();
} else {
// if the call to validate() returns false, the error messages will appear automatically.
// you can run any extra code you need here
}
}
)
]
));
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…