Home > database >  Flutter TextField: Cursor position goes to one before the last when selecting a RTL TextField
Flutter TextField: Cursor position goes to one before the last when selecting a RTL TextField

Time:05-21

I have a TextField with its textDirection set to rtl (Right-to-Left). When I select the TextField, I expect the cursor go to the end, as usual, but cursor goes to one position before the end.

this is the result

 TextField(
    textDirection: TextDirection.rtl,
    controller: widget.controller,
    decoration: InputDecoration(
      contentPadding: EdgeInsets.all(8),
      isDense: true,
      focusedBorder: OutlineInputBorder(
        borderSide: BorderSide(
          width: 2,
          color: Theme.of(context).primaryColor,
        ),
        borderRadius: BorderRadius.circular(8),
      ),
      enabledBorder: OutlineInputBorder(
        borderSide: BorderSide(
          width: 1.7,
          color: Colors.grey.withOpacity(0.3),
        ),
        borderRadius: BorderRadius.circular(8),
      ),
    ),
  ),
);

How can I make the cursor appear at the end instead?

UPDATE: I realized that specifying controller in the TextField make the problem appear. but i need cotroller in this situation.

CodePudding user response:

You can control cursor position by using TextSelection.

I didn't test Arabic environment, but try this.

offset value means position of cursor, so test 0 or (widget.controller.text.length)

   TextField(
        textDirection: TextDirection.rtl,
        controller: widget.controller
                    ..selection = TextSelection.fromPosition(TextPosition(offset: 0)),
        decoration: InputDecoration(
          contentPadding: EdgeInsets.all(8),
          isDense: true,
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(
              width: 2,
              color: Theme.of(context).primaryColor,
            ),
            borderRadius: BorderRadius.circular(8),
          ),
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(
              width: 1.7,
              color: Colors.grey.withOpacity(0.3),
            ),
            borderRadius: BorderRadius.circular(8),
          ),
        ),
      ),
    );

CodePudding user response:

You can try this action to move the cursor to the end of the text. Then place this controller in the controller in TextField.:

late TextEditingController _textEditingController;

@override
  void initState() {
    _textEditingController = TextEditingController(text: widget.text);
    _textEditingController.selection = TextSelection.fromPosition(
        TextPosition(offset: _textEditingController.text.length));
    super.initState();
  }
  • Related