How to focus the cursor to end of the strings in flutter

In Flutter development, I came across the situation where we need to move the cursor focus to the end of the previously assigned text. The focus should be triggered during the initial load of the widget.

Solution:

To achieve the result I need to understand these simple piece of the code.

First I am loading the TextEditingController with default value s assigned.

String firstNameTxt = "Hello";
TextEditingController firstName = TextEditingController(text: firstNameTxt);

Now I need to take the length of the variable firstNameTxt and assigned to the variable firstNameLen.

String firstNameTxt = "Hello";
String firstNameLen = firstNameTxt.length;
TextEditingController firstName = TextEditingController(text: firstNameTxt);

Then I have to mention the position of the string selection. If I mention the total length of the firstNameTxt that is the position of the last character of the text, it will focus to the end of the text in the text box.

String firstNameTxt = "Hello";
String firstNameLen = firstNameTxt.length;
TextEditingController firstName = TextEditingController(text: firstNameTxt);
firstName.selection = TextSelection.fromPosition(TextPosition(offset: firstNameLen ));

Thats all, Now on loading the TextEditingController, the cursor focus has been pointed to the end of the all text.

Updated: March 13, 2024 — 10:13 am