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))),
),
),
...
}
}
Run Code Online (Sandbox Code Playgroud)
发生这种情况是因为您正在方法中设置文本build
。该build
方法可以随时调用,例如当键盘收缩时,因为 UI 需要对此做出反应。
这意味着您应该将此代码移至initState
:
@override
void initState() {
_note = widget._note;
_titleController.text = _note.title;
_descriptionController.text = _note.description;
super.initState();
}
Run Code Online (Sandbox Code Playgroud)
initState
仅当您的小部件插入构建树时调用一次。
我不知道为什么这只发生在其中一个TextFields
。我假设您TextController
在其他地方使用 's 来设置Note
's 内容,这可能会导致此行为。
此外,_
当您_note
从.StatefulWidget
widget._note
State