Flutter中可以使用GlobalKey来获取组件的状态和设置属性,从而实现表单的验证。
- 在需要验证的表单中,给每个输入框设置一个GlobalKey。
final _formKey = GlobalKey<FormState>();
final _emailKey = GlobalKey<FormFieldState<String>>();
final _passwordKey = GlobalKey<FormFieldState<String>>();
- 在Form组件中添加一个全局key并注册验证函数。
Form(
key: _formKey,
child: Column(
children: [
TextFormField(
key: _emailKey,
validator: (value) {
if (value.isEmpty) {
return 'Please enter your email';
}
return null;
},
),
TextFormField(
key: _passwordKey,
validator: (value) {
if (value.isEmpty) {
return 'Please enter password';
}
return null;
},
),
RaisedButton(
onPressed: () {
if (_formKey.currentState.validate()) {
// Do something
}
},
)
],
),
);
- 在提交按钮的事件中,通过GlobalKey获取对应输入框的状态,使用validate()方法触发表单验证。如果验证通过,执行相关操作。
RaisedButton(
onPressed: () {
if (_formKey.currentState.validate()) {
String email = _emailKey.currentState.value;
String password = _passwordKey.currentState.value;
// Do something
}
},
),