代码:
final GlobalKey<FormState> _formKey = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => _formKey.currentState.validate(),
),
body: Form(
key: _formKey,
child: FormField(
builder: (state) => TextField(),
validator: (string) {
print(string); // always prints null
return null;
},
),
),
);
}每当我试图验证表单时,FormField验证器总是返回null。我认为我使用它不正确,谁能示范如何在上述情况下使用FormField?
PS:
我不是在找TextFormField,我知道我的工作可以很容易地完成。
发布于 2020-06-07 08:15:26
根据医生的说法:
builder→FormFieldBuilder
函数,它返回表示此表单字段的小部件。它作为输入传递表单字段状态,其中包含该字段的当前值和验证状态。
在您的代码中,您将返回一个TextformField作为表示此表单字段的小部件。如果您想要验证,那么在validate小部件中使用TextFormField属性的唯一方法是:
final GlobalKey<FormState> _formKey = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () => _formKey.currentState.validate(),
),
body: Form(
key: _formKey,
child: FormField(
builder: (state) => TextFormField(validator: (string) {
print(string);
return null;
},),
),
),
);
}https://api.flutter.dev/flutter/widgets/FormField-class.html
https://stackoverflow.com/questions/62242463
复制相似问题