I have been looking for controlling each widget in a page using a separate key. Can anyone suggest me best way for that? I tried in Form like
final formKey = GlobalKey<FormState>();
Form(
key: formKey,
),
But I am confused while working with Container, Card, and others widget. Can any suggest what should I follow and where?
You don't need formKey for Container, Card or any other widget which is not related with .
If you create Form Widget, you need to give it a TextFormField child, which inherits FormState.
The thing is here, probably you'll have multiple TextFormField widgets, so instead of creating and handling them one by one keys for each TextFormField, you create Form Widget to group your TextFormFields, then assign formKey once and use it at all.
Your formKey has no business with other type of widgets.
Explainer code:
Widget buildFormTree() {
final formKey = GlobalKey<FormState>();
String text1;
String text2;
return Column(
children: <Widget>[
Form(
key: formKey,
child: Column(
children: <Widget>[
TextFormField(
// key: asd, //No need
onSaved: (text) {
text1 = text;
},
),
TextFormField(
// key: qwe, // No need
onSaved: (text) {
text2 = text;
},
),
],
),
),
RaisedButton(
child: Text('Save Forms'),
onPressed: () {
///to trigger onSaved callback
formKey.currentState.save();
},
)
],
);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments