If you want to set the cursor position at the end of the text value or text field, then TextSelection.collapsed() is useful.
It works together with TextEditingController().
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Riverpod App"),
),
body: TextWidget(),
),
);
}
}
class TextWidget extends StatefulWidget {
const TextWidget({Key? key}) : super(key: key);
@override
State<TextWidget> createState() => _TextWidgetState();
}
class _TextWidgetState extends State<TextWidget> {
var _title =TextEditingController(text: "I am here");
@override
Widget build(BuildContext context) {
return TextField(
textAlign: TextAlign.center,
controller: _title,
onChanged: (value) => setState(() {
int offset = _title.selection.baseOffset;
print("......$offset...");
_title.selection =
TextSelection.collapsed(offset: offset);
}));
}
}
Here offset plays an important rule where the cursor is placed. With current offset, the cursor would be placed right after each letter as you type.
You may change the offset value to see the better.