在Flutter中使用控制器设置文本时,TextField光标不移动

时间:2019-01-05 17:51:41

标签: flutter

我正在使用StreamBuilder来监听对TextField的更改并相应地更新TextField errorText。但是现在我也想通过快照数据将一些文本设置为TextField。但是键入时光标根本没有移动。下面是我的代码:

Widget goalField() {
    return StreamBuilder(
        stream: _bloc.goalMessage,
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
          return TextField(
            controller: TextEditingController(text: snapshot.data),
            keyboardType: TextInputType.multiline,
            maxLines: 3,
            onChanged: _bloc.changeGoalMessage,
            decoration: InputDecoration(
                hintText: "Enter your goal here", errorText: snapshot.error),
          );
        });
  }

它成一个循环。我该如何解决?

1 个答案:

答案 0 :(得分:0)

我已经使用 _textEditingController.value.copyWith(text: snapshot.data) 尝试了评论中建议的解决方案,但每次更新 TextField 上显示的值时,光标似乎都位于文本的开头。

Demo 1 using text controller value

对我有用的是使用 _textEditingController.selection.copyWith(extentOffset: _textEditingController.text.length) 在 TextField 上设置偏移量。

Demo 2 using selection offset

您可以通过以下方式将其应用于代码片段。

var _textEditingController = TextEditingController();

...

StreamBuilder(
    stream: _bloc.goalMessage,
    builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
        _textEditingController.text = snapshot.data;
        _textEditingController.selection = _textEditingController.selection.copyWith(extentOffset: _textEditingController.text.length);
        return TextField(
            controller: _textEditingController,
            keyboardType: TextInputType.multiline,
            maxLines: 3,
            onChanged: _bloc.changeGoalMessage,
            decoration: InputDecoration(
                hintText: "Enter your goal here", errorText: snapshot.error),
        );
    },
);