问题描述
我向您解释我目前正在尝试强制填写通过邮件发送的信息发送的信息。
如果可以有一个解释,以便我了解将代码添加到我的表单中是如何工作的。
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Demande'),),body: Container(
color: Color(0xffd8edff),child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),child: Card(
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(15.0),child: TextFormField(
controller: nomController,decoration: Inputdecoration(
labelText: 'Nom:',Padding(
padding: const EdgeInsets.all(15.0),child: TextFormField(
controller: prenomController,decoration: Inputdecoration(
labelText: 'Prénom:',keyboardType: TextInputType.name,child: TextFormField(
controller: emailController,decoration: Inputdecoration(
labelText: 'E-mail:',hintText: 'Ex: [email protected]',RaisedButton(
onpressed: () async {
showDialog(
context: context,barrierdismissible: false,builder: (BuildContext context) {
// return object of type Dialog
解决方法
您需要使用 Form
小部件包装整个表单。
然后您可以将 GlobalKey<FormState>
传递到 Form
中以获取对它的引用,您可以在其他方法中使用该引用
您应该在 initState()
类的 State
中创建表单键(确保您使用的是 StatefulWidget
)。
完成此操作后,您可以将 validator
传递给您的 TextFormField
。 validator
接受一个字符串,如果输入有效则返回 null
,如果输入无效则返回错误消息字符串。
然后,在提交按钮上,您可以调用 formKey.currentState.validate()
。如果任何文本字段未通过其验证器,则此方法返回 false
。
例如:
GlobalKey<FormState> _formKey;
@override
void initState() {
super.initState();
_formKey = GlobalKey();
}
@override
Widget build(BuildContext context) {
return Form(key: _formKey,child: Column(
children: [
TextFormField(
validator: (value) {
if (value.isEmpty) return 'Please enter a value';
else return null;
},controller: ... // whatever controller you are using
),FlatButton(
child: Text('Submit'),onPressed: () {
if (_formKey.currentState.validate()) {
// if this returns true,all the text fields have got good data (i.e. all fields are non-empty)
doSomething();
} else {
// if the call to validate() returns false,the error messages will appear automatically.
// you can run any extra code you need here
}
}
)
]
));
}