How to use textEditiing controller with Provider in Flutter

Issue

I am using provider for state management. I am in a situation where there are multiple types of fields in my form. The problem is with text-field
Whenever I change Text it is behaving weirdly like the text entered is displayed in reverse order.

class MyProvider with ChangeNotifier{
  String _name;
  String get name => _name;
  setname(String name) {
    _name = name;
    notifyListeners();
  }
}

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

    final TextEditingController _nameController = TextEditingController(
        text: myProvider.name,
    );

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

}

Solution

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,
    );
  }
}

Answered By – Igor Kharakhordin

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.