flutter - 移除键盘后,TextField 中的文本消失
问题描述
TextField
当我从视图中移除键盘时,在我的小部件中输入的文本会消失。
有两个TextField
,标题和描述。上述问题仅出现在标题上,而不会出现在描述上。
以下是该方法的相关摘录build
:
@覆盖
Widget build(BuildContext context) {
_note = widget._note; // This is coming from StatefulWidget Class above
TextStyle textStyle = Theme.of(context).textTheme.title;
_titleController.text = _note.title;
_descriptionController.text = _note.description;
return Scaffold(
body: ListView(
children: <Widget>[
Padding(
padding: EdgeInsets.all(15.0),
child: TextField(
style: textStyle,
controller: _titleController,
decoration: InputDecoration(
labelText: "Title",
labelStyle: textStyle,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0))),
),
),
Padding(
padding: EdgeInsets.all(15.0),
child: TextField(
style: textStyle,
controller: _descriptionController,
decoration: InputDecoration(
labelText: "Description",
labelStyle: textStyle,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0))),
),
),
...
}
}
解决方案
发生这种情况是因为您在build
方法中设置文本。这个build
方法可以在任何时候被调用,例如当键盘收缩时,因为 UI 需要对此做出反应。
这意味着您应该将此代码移至initState
:
@override
void initState() {
_note = widget._note;
_titleController.text = _note.title;
_descriptionController.text = _note.description;
super.initState();
}
initState
仅当您的小部件插入构建树时才调用一次。
我不确定为什么这只发生在其中一个TextFields
's. 我假设您在TextController
其他地方使用 's 来设置Note
's 内容,这可能会导致这种行为。
此外_
,当_note
您StatefulWidget
从.widget._note
State
推荐阅读
- c - 独立的 C 应用程序
- android - Cordova 中的图像预览
- python - 通过python电子邮件模块发送的嵌入图片的电子邮件被过滤为垃圾邮件
- jmeter - 如何跳过特定列中没有数据的行
- netbeans - 插入 C 或汇编程序文件中的自定义语言的 Netbeans 语法突出显示
- java - ApiOriginFilter.java 是如何生成的
- excel - 需要一种在 Excel VBA 中使循环更快的方法
- r - 匹配并列出来自 .xlsx 的 R 中的列项
- sql - Python cx_oracle 将变量与项目列表绑定
- azure - 如何在 Azure 数据工厂 V1/V2 中将带 BOM 的 UTF-8 编码文件转换为不带 BOM 的 UTF-8 编码文件?