Flutter Cursor of TextField moves to Position 0 after setState Flutter Cursor of TextField moves to Position 0 after setState dart dart

Flutter Cursor of TextField moves to Position 0 after setState


The issue is that you are creating a new TextEditingController each time your widget is rebuilt. The widget is being rebuilt on every character that is typed.

You just need to move the TextEditingController outside of the widget build function. And also move the c.addListener to the widget's initState function. This way the TextEditingController is only created one time, and the listener is only added one time.

PS: It is also good to dispose your controller when the widget is disposed

class MyPage extends StatefulWidget {  @override  _MyPageState createState() => _MyPageState();}class _MyPageState extends State<MyPage> {  String name = '';  TextEditingController c = new TextEditingController();  @override  void initState() {    c.addListener(() {      setState(() {        name = c.text;      });    });    super.initState();  }  @override  void dispose() {    c.dispose();    super.dispose();  }  @override  Widget build(BuildContext context) {    return Scaffold(        body: Center(            child: Column(children: [      Text('Hello, ' + name + '!'),      TextField(controller: c)    ])));  }}


I have modified your code, you just need to change your TextEditingController see below.

class _MyPageState extends State<MyWidget> {  // initialize to empty string  String name = "";   @override  Widget build(BuildContext context) {    // this is how textEditingController should be    final TextEditingController c = TextEditingController.fromValue(            new TextEditingValue(                text: name,                selection: new TextSelection.collapsed(                    offset: name.length)));        c.addListener(() {         setState(() { name = c.text;});      });          return Scaffold(         body: Center(            child: Column(children: [                Text('Hello, ' + name + '!'),               TextField(controller: c)      ])));  }}