Home > front end >  TextField with long text, horizontal scroll reset to start - Flutter
TextField with long text, horizontal scroll reset to start - Flutter

Time:05-28

Building a stateful widget with a textfield wrapped within a Container of specific width. Now, when I type a long text in the textfield, the view scrolls right as you type (works as expected). But when I tap outside of the textfield, I've unfocused the textField. When I unfocus, how do I programatically reset the view of the textfield back to the beginning of the text? i.e. Move the horizontal scroll back to the beginning?

Here's the textField widget

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);
      },
    )
);

See the mid part of the gif, when I unfocus the textfield, I'd like to push the view/scroll back to the beginning of the widget. Tried rebuild the widget, but doesn't work.

enter image description here

CodePudding user response:

You can use ScrollController inside TextField and while textfiled get unfocused jump to start.

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",
            ),
          ),
        ],
      ),
    ));
  }
}
  • Related