Home > Mobile >  How to move to the right end the cursor on TextFormField with Flutter?
How to move to the right end the cursor on TextFormField with Flutter?

Time:01-09

I have a TextFormField widget that displays values on the right end, and every time the field is selected, the cursor is at the beginning of the text, like this:

enter image description here

What I would like to get, is that the cursor is always displayed on the right side when the field is selected (with a tap or so). What I tried so far is:

  @override
  void initState() {
    sellingPriceController.numberValue = 0;

    sellingPriceController.selection = TextSelection.fromPosition(TextPosition(offset: sellingPriceController.text.length));
    super.initState();
  }

but it seems not working. Any idea?

CodePudding user response:

You need to create a FocusNode for that TextFormField and listen to its changes. Whenever the focus changes and the TextFormField has the focus, move the cursor to the end based on the text inside sellingPriceController.

Here's an example:

class MyHomePage extends StatefulWidget {
  const MyHomePage({
    Key? key,
  }) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late final sellingPriceController = TextEditingController(text: '0');
  late final focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    focusNode.addListener(onSelection);
  }

  void onSelection() {
    if (focusNode.hasFocus) {
      sellingPriceController.selection = TextSelection.fromPosition(
        TextPosition(
          offset: sellingPriceController.text.length,
        ),
      );
    }
  }

  @override
  void dispose() {
    sellingPriceController.dispose();
    focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: SizedBox(
        width: 300,
        child: TextFormField(
          textAlign: TextAlign.right,
          focusNode: focusNode,
          controller: sellingPriceController,
        ),
      ),
    );
  }
}

Additional Note: if you want to force the cursor to always be on the right side, then also listen to the sellingPriceController changes by adding the following to the initState:

sellingPriceController.addListener(onSelection);

With this, whenever the user interacts with the field (insert character, remove one, taps somewhere, etc.), the cursor will always be at the end.

  •  Tags:  
  • Related