带有长文本的TextField,水平滚动重置为开始 - Flutter

TextField with long text, horizontal scroll reset to start - Flutter

构建一个有状态的小部件,其中包含一个包含在特定宽度的容器中的文本字段。现在,当我在文本字段中键入长文本时,视图会在您键入时向右滚动(按预期工作)。但是,当我在文本字段之外点击时,我没有关注文本字段。当我失去焦点时,如何以编程方式将文本字段的视图重置回文本的开头?即,将水平滚动条移回开头?

这是文本字段小部件

textContainer = Container(
    width: MediaQuery.of(context).size.width * 0.68,
    child: Focus(
      child: TextField(
        keyboardType: TextInputType.text,
        textCapitalization: TextCapitalization.sentences,
        onSubmitted: onSubmit,
        controller: textController,
        focusNode: widget.focusNode,
        maxLines: 1,
        autofocus: widget.isNew,
        cursorColor: Colors.white,
        style: const TextStyle(
            fontSize: 16.0,
            fontFamily: 'Inter',
            fontWeight: FontWeight.normal,
            color: Colors.white
        ),
        decoration: const InputDecoration(
          border: InputBorder.none,
        ),
        onChanged: (text) {
          Task task = taskBox.get(widget.task.id);
          task.text = text;
          taskBox.put(widget.task.id, task);
        },
      ),
      onFocusChange: (hasFocus) {
        showDeleteBtn(hasFocus);
      },
    )
);

查看 gif 的中间部分,当我取消对文本字段的关注时,我想将 view/scroll 推回到小部件的开头。尝试重建小部件,但不起作用。

您可以在 TextField 中使用 ScrollController,当文本字段未聚焦时跳转到开始。

class _TOSState extends State<TOS> {
  late final FocusNode textInputFocusNode = FocusNode()
    ..addListener(() {
      debugPrint(textInputFocusNode.hasFocus.toString());
      if (!textInputFocusNode.hasFocus) {
        controller.jumpTo(0);
      }
    });
  ScrollController controller = ScrollController();

  @override
  void dispose() {
    textInputFocusNode.removeListener(() {});
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus();
      },
      child: Column(
        children: [
          TextField(
            scrollController: controller,
            focusNode: textInputFocusNode,
            maxLines: 1,
            decoration: const InputDecoration(
              hintText: "TYpe",
            ),
          ),
        ],
      ),
    ));
  }
}