文本框的创建和设定
Flutter 提供的文本框组件: TextField
和 TextFormField
。
TextFormField
内部封装了一个 TextField
,并被集成在表单组件 Form
中。如果需要对文本输入进行验证,或者需要与其他表单组件 FormField
交互联动,可以考虑使用 TextFormField
。
TextField的常用属性:
- controller: TextEditingController 文本控制器
- decoration: InputDecoration 输入框样式
- style: TextStyle 文字样式
- autofocus:bool 自动聚焦,
- minLines: 最少几行
- maxLines:
- maxLength: 字符数
- onChanged: 输入框的内容改变时触发函数
- onSubmitted: 调用提交时触发函数
- keyboardType: TextInputType,键盘类型
- obscureText = false, 是否隐藏内容,例如密码格式
- autocorrect = true, 是否自动校正
TextFormField的常用属性(上面TextField的常用属性都是):
- initialValue: 初始化的值
- validator: 校验函数,返回null通过,返回其他的报错
表单验证
为了验证表单,我们需要使用到步骤 1 中的 _formKey
。使用 _formKey.currentState()
方法去访问 FormState
,而 FormState
是在创建表单 Form
时 Flutter 自动生成的。
FormState
类包含了 validate()
方法。当 validate()
方法被调用的时候,会遍历运行表单中所有文本框的 validator()
函数。如果所有 validator()
函数验证都通过,validate()
方法返回 true
。如果有某个文本框验证不通过,就会在那个文本框区域显示错误提示,同时 validate()
方法返回 false
。
使用Form
设置全局key值,方便获取表单的states,validator:为校验函数,这里只做了不为空的校验,
_formKey.currentState!.validate()通过key值获取form的states,然后调用 validate()校验函数。
_formKey.currentState!.save(); 调用保存输入框的函数。
Form(
key: _formKey, //
child: Column(
children: <Widget>[
TextFormField(
keyboardType: TextInputType.emailAddress, // 键盘类型
decoration: InputDecoration(
labelText: 'email address',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter you email address';
}
return null;
},
onSaved: (newValue) {
user['email'] = newValue.toString();
},
),
SizedBox(
height: 20,
),
TextFormField(
keyboardType: TextInputType.visiblePassword,
obscureText: true,
decoration: InputDecoration(
labelText: 'visiblePassword',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
onSaved: (newValue) {
user['password'] = newValue.toString();
},
),
SizedBox(
height: 20,
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
print(user);
}
},
child: const Text('Submit'),
),
),
],
),
);
结果
输入内容后,点击提交按钮,可以看到打印出了输入的信息。