Search code examples
fluttertextfield

Flutter TextField Focus Node Request focus selects text


I have an alert dialog with a TextField and a Drop Down Button on top of it. I want the Text Field to gain the focus back once an option in a drop down menu was selected. I use 2 separate FocusNodes for that, one for TextField and one for DropDown Button. But instead of placing a cursor at the end of the text in a text field (as if it was tapped by a user) the text gets selected and I need to tap it once more to see the cursor.

For some reason when I tap outside on other buttons the cursor stays at the end of the text but when I select something from a drop down menu the text focus is lost. And when I request it again all it does is just select everything.

It works here: enter image description here

But not here:

But not here

Here is a part of my code:

class _BasicWindowState extends State<BasicWindow> {
  final TextEditingController textController = TextEditingController();
  FocusNode textFocus = FocusNode();
  FocusNode dropDownFocus = FocusNode();
TextField( focusNode: textFocus,
          onTapOutside: (event) => textFocus.requestFocus())

DropdownButton(
     focusNode: dropDownFocus,
     onChanged: (String? newList) {
        dropDownFocus.unfocus();
        textFocus.requestFocus();
        textController.selection =TextSelection.collapsed(offset: textController.text.length);}
               

I tried adding TextFieldTapRegion but it didn't help.


Solution

  • Try to put selection in Future.delayed like below

    Future.delayed(Duration(milliseconds: 100), () 
    { 
        textController.selection = TextSelection(baseOffset: 0, 
        extentOffset: textController.text.length, );
    });