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).
ChangeNotifier
class as follows:class AmountManager extends ChangeNotifier {
String amount;
void changeAmount(String newAmount) {
amount = newAmount;
notifyListeners();
}
}
TextField
:class MyTextField extends StatelessWidget {
@override
Widget build(BuildContext context) {
return TextField(
//some decorations here
onChanged(value) {
Provider.of<AmountManager>(context).changeAmount(value);
},
);
}
}
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,
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.