How to use textEditiing controller with Provider in Flutter

To store the text from the TextField into Provider you need to send the text property from the controller to the provider:

_nameController.addListener(() {
    myProvider.setName(_nameController.text);
});

This would also remove the problem you are getting the reverse text in the TextField


It happens because new instance of TextEditingController is created on every widget build, and information about current cursor position (TextEditingValue) is getting lost.

Create a controller once in initState method and dispose of it in dispose method.


class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  TextEditingController _nameController;

  @override
  void initState() {
    final MyProvider myProvider = Provider.of<MyProvider>(context, listen: false);

    super.initState();
    _nameController = TextEditingController(text: myProvider.name);
  }

  @override
  void dispose() {
    _nameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final MyProvider myProvider = Provider.of<MyProvider>(context);

    return TextField(
        controller: _nameController,
        onChanged: myProvider.setname,
    );
  }
}