Search code examples
flutter

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


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.


Solution

  • I think this because of each arabic character is encoded as 2 to 4 bytes.

    Any way this code can do the trick

    TextField(
         onTap: (){
              if(controller.selection == TextSelection.fromPosition(TextPosition(offset: controller.text.length -1))){
                 setState(() {
                     controller.selection = TextSelection.fromPosition(TextPosition(offset: controller.text.length));
                 });
               }
         },
         controller: controller,
         ...
    );