flutterdarttextfieldautofocus

How to make autofocus on first line in TextField that has already some text?


I want to make TextField where user can click on any line and start writing from there. So I had an idea to just make new note that just has already these "\n" at start of any line but now I don't know how to set autofocus on first line.

photo of my note where autofocus focus on last sign

class NewNoteBodyState extends State<NewNoteBody> {
  final myController = TextEditingController();
  // late FocusNode myFocusNode;

  @override
  void initState() {
    super.initState();
    widget.controller.text = widget.controller.text;
    widget.controller.text = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
    // myFocusNode = FocusNode();
  }

  // @override
  // void dispose() {
  //   super.dispose();
  //   myFocusNode.dispose();
  // }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 10),
      child: TextField(
        expands: true,
        // focusNode: myFocusNode,  
        autofocus: true,
        controller: widget.controller,
        maxLines: null,
        decoration: const InputDecoration(
          border: InputBorder.none,
        ),
      ),
    );
  }
}

I looked at TextField atributes and tried something with focusNode but I don't get it.


Solution

  • You can achieve this by setting the selection to 0 position in text like this:

    widget.controller.selection = TextSelection.fromPosition(TextPosition(offset: 0));
    

    which should place the cursor at the beginning of your initial text.