Form
您将需要使用Widget 和它自己的密钥来包装要单独验证的每个字段:
class TextFormFieldValidation extends StatefulWidget {
@override
_TextFormFieldValidationState createState() => _TextFormFieldValidationState();
}
class _TextFormFieldValidationState extends State<TextFormFieldValidation> {
List<GlobalKey<FormState>> _formKeysList= [
GlobalKey<FormState>(),
GlobalKey<FormState>(),
];
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Form(
key: _formKeysList[0],
child: TextFormField(
validator: (value) => 'Bad',
),
),
Form(
key: _formKeysList[1],
child: TextFormField(
validator: (value) => 'Bad',
),
),
RaisedButton(
child: Text('Validate 1'),
onPressed: () => _formKeysList[0].currentState.validate(),
),
RaisedButton(
child: Text('Validate 2'),
onPressed: () => _formKeysList[1].currentState.validate(),
),
RaisedButton(
child: Text('Reset'),
onPressed: () => _formKeysList.forEach((key) => key.currentState.reset()),
),
],
);
}
}