首页 > 解决方案 > 移除键盘后,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))),
                      ),
                    ),  
           ...
          }
        }

显示和删除的键盘截图。

标签: flutter

解决方案


发生这种情况是因为您在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 内容,这可能会导致这种行为。
此外_,当_noteStatefulWidget从.widget._noteState


推荐阅读