Function in ChangeNotifier Class Not Called

Issue

I have a Flutter App with Provider as a State Manager. The ChangeNotifierProvier is at the very top of my app (ie. above MaterialApp widget).

  1. I have a ChangeNotifier class as follows:
class AmountManager extends ChangeNotifier {
  String amount;
  void changeAmount(String newAmount) {
    amount = newAmount;
    notifyListeners();
  }
}
  1. Then I have another class with a TextField :
class MyTextField extends StatelessWidget {
  @override 
  Widget build(BuildContext context) {
    return TextField(
      //some decorations here
      onChanged(value) {
        Provider.of<AmountManager>(context).changeAmount(value);
      },
    );
  }
}
  1. And in another class under the Main App, I call the amount variable:
class MyText extends StatelessWidget {
  @override 
  Widget build(BuildContext context) {
    return Text(
      Provider.of<AmountManager>(context).amount,
    );
  }
}

The problem is the Provider.of(...) method cannot be called. I watched some tutorials and couldn’t find out the reason behind it. If I use static text instead of the AmountManager object, it works. The program only uses the initial value of amount in MyText class.

What do you think I’m wrong with?

Thank you in advance,

Solution

You need listen: false when you use Provider.of() in onChanged.

onChanged: (value) {
  Provider.of<AmountManager>(context, listen: false).changeAmount(value);
},

See this for details.

Answered By – kaboc

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.