Flutter Cursor of TextField moves to Position 0 after setState

810

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)
    ])));
  }
}
Share:
810
julienduchow
Author by

julienduchow

Updated on December 27, 2022

Comments

  • julienduchow
    julienduchow over 1 year

    I want to display something in a Text whenever a TextFields text changes:

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

    The Text updates as exspected, but the problem is that the Cursor of the TextField moves to position 0 each time I enter a character.