1

I have a TextField which has a default text in it from the beginning. I want the cursor to be placed at the end of the existing text when the TextField receives focus (possibly with the condition that the text should not have already been modified from the default text).

I've tried setting the controller.selection which didn't work. I also tried using a FocusNode:

focusNode: FocusNode()..addListener((){
    if( !record.isCommentModified )
        record.textEditingController.selection = TextSelection.collapsed(offset: record.comment.length);
})

It does work, but one side effect is that multiple textfields look like they have focus at the same time. How can I prevent this? Or even better, is there a better way of achieving what I want?

Magnus
  • 17,157
  • 19
  • 104
  • 189
  • @pskink You mean in the `FocusNode`? It has the same effect as `TextSelection.collapsed()` i.e. it works but messes up the focus of other controls so that multiple TextFields can be focused at the same time... – Magnus Mar 06 '19 at 09:38
  • @pskink Strange... I'm trying it on an API 26 emulator, it shows text cursors in the TextFields even after focusing another TextField (but only the last focused one receives text when typing). – Magnus Mar 06 '19 at 10:58

1 Answers1

0

If there's a value set on a TextField, by default the cursor is positioned at the end of the text/value when focused. Let me know if the behavior you've encountered was different.

TextFields need to have individual FocusNode. Since you're using a single FocusNode for multiple, once one TexField is focused it appears that there are multiple TextFields in focus.

As for tracking which TextField contains text, individual TextEditingController is needed as well. What I can suggest is to create a List of FocusNode and TextEditingController for the TextFields.

late List<FocusNode> focusNodeList;
late List<TextEditingController> textController;

@override
void initState() {
  super.initState();
  // Initialize both List
  textController = List<TextEditingController>.generate(
      length, (index) => TextEditingController());
  focusNodeList = List<FocusNode>.generate(length, (index) {
    var focusNode = FocusNode();
    focusNode.addListener(() {
      // Do something
    });
    return focusNode;
  });
}

and set them on your TextField

TextField(
  controller: textController[0],
  focusNode: focusNodeList[0],
),
TextField(
  controller: textController[1],
  focusNode: focusNodeList[1],
),
...
Omatt
  • 8,564
  • 2
  • 42
  • 144