如何调用特定验证器而不是使用 `form.validate()` 同时调用所有验证器?
How to call specific validator instead of calling all the validators in same time by using `form.validate()`?
这是代码:
if (form.validate()) {
// Text forms was validated.
if (mounted) {
setState(() {
_isButtonEnabled = true;
});
}
form.save();
}
我想为特定的 TextFormField 调用特定的验证器
您需要使用 Form
小部件和它自己的密钥来包装您想要单独验证的每个字段:
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()),
),
],
);
}
}
Joao 的回答是正确的,但也设计过度了。您可以改为为要独立验证的每个字段声明一个 GlobalKey
:
GlobalKey<FormFieldState> fieldKey = GlobalKey();
将其分配给您要验证的TextFormField
:
TextFormField(
key: fieldKey,
...
然后使用密钥验证该字段:
bool valid = fieldKey.currentState.validate();
这是代码:
if (form.validate()) {
// Text forms was validated.
if (mounted) {
setState(() {
_isButtonEnabled = true;
});
}
form.save();
}
我想为特定的 TextFormField 调用特定的验证器
您需要使用 Form
小部件和它自己的密钥来包装您想要单独验证的每个字段:
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()),
),
],
);
}
}
Joao 的回答是正确的,但也设计过度了。您可以改为为要独立验证的每个字段声明一个 GlobalKey
:
GlobalKey<FormFieldState> fieldKey = GlobalKey();
将其分配给您要验证的TextFormField
:
TextFormField(
key: fieldKey,
...
然后使用密钥验证该字段:
bool valid = fieldKey.currentState.validate();