flutter - 当我单击继续时,值不会保留在文本表单字段中,然后当我返回页面时,值是空的 请注意,我使用了页面视图
问题描述
我正在尝试制作注册页面,所以我使用了像这样的页面视图文本表单字段消失了。当我在页面视图中移动到新页面并返回页面时,所有页面都会发生这种情况。用户填写的信息从字段中消失了,变成了空白!为什么?
Form(
key: EmailKeys.formKey,
child: Column(
children: [
const Text(
"Create an account, It's free",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 16, color: Colors.grey),
),
const SizedBox(
height: 40,
),
TextFormField(
onFieldSubmitted: (val) {
EmailKeys.formKey.currentState!.setState(() {
email = val.trim();
});
EmailKeys.formKey.currentState!.save();
},
textInputAction: TextInputAction.done,
inputFormatters: [LengthLimitingTextInputFormatter(100)],
obscureText: false,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: "Email Address",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
),
labelStyle: TextStyle(color: Colors.grey[400]),
floatingLabelStyle:
const TextStyle(color: Colors.blueGrey, fontSize: 18),
),
validator: (value) {
if (value!.isEmpty) {
return 'Email address is required';
} else if (!value.contains("@")) {
return "Email address should contain ' @ ' symbol";
}
},
onChanged: (value) {
email = value.trimLeft();
},
onSaved: (val) {
setState(() {
email = val!;
});
print(email);
},
controller: _emailCtrl,
),
],
),
),
解决方案
在 TextFormField 中使用 TexEditingController 来保存和检索数据https://api.flutter.dev/flutter/widgets/TextEditingController-class.html
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
final TextEditingController _controller = TextEditingController();
@override
void initState() {
super.initState();
_controller.addListener(() {
final String text = _controller.text.toLowerCase();
_controller.value = _controller.value.copyWith(
text: text,
selection:
TextSelection(baseOffset: text.length, extentOffset: text.length),
composing: TextRange.empty,
);
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(6),
child: TextFormField(
controller: _controller,
decoration: const InputDecoration(border: OutlineInputBorder()),
),
),
);
}
}
推荐阅读
- r - 使用 rvest 提取 xml 路径
- python - 无法在 keras 中连接两个输入层。
- php - file_get_contents() 标头已发送
- javascript - 为什么单击此按钮时会出现随机空格?
- haskell - 如何使用 QuickCheck 在范围内选择一个值?
- asp.net - 如何将ckeditor 5与asp.net集成并在ckeditor5中安装插件latex equation editor
- php - Codeigniter 电子邮件中的电子邮件 html 输出
- ios - Issue while handle user typing notification using notificatincenter
- java - how to set a timer to update data in firebase database
- sql-server - Calling stored procedure from MS Access results in error 3146