I am new to flutter.
I am trying to display an integer value. The value changes on some conditions. Now I am trying to update the widgets and the displaying value of the integer with Provider / ChangeNotifier but it doesn't work.
My tokens_provider.dart:
class TokenProvider extends ChangeNotifier {
int value = 10;
void decreaseTokens() async {
final SharedPreferences prefs = await _prefs;
value--;
prefs.setInt('_tokens', value);
notifyListeners();
}
}
method where I call decreaseTokens:
Future<void> decreaseTokens() async {
var tokens = context.read<TokenProvider>();
if (tokens.value! > 0) tokens.decreaseTokens();
final SharedPreferences prefs = await _prefs;
await prefs.setInt('_tokens', tokens.value!);
setState(() {});
}
my Consumer Widget:
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<TokenProvider>(
create: (context) => TokenProvider(),
builder: (context, child) {
return Consumer<TokenProvider>(
builder: (context, tokens, child) {
return Scaffold(
backgroundColor: Constants.backgroundColor,
appBar: AppBar(
leadingWidth: 100,
leading: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(width: 15),
Image.asset('assets/images/coin.png', scale: 4),
SizedBox(width: 3),
Text('${tokens.value}', style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
color: Colors.green),),
SizedBox(width: 3),
Text("Token",
style: TextStyle(fontWeight: FontWeight.bold),)
]
),
But for some reason, it displays everytime 10 as value. It doesn't change at any action
I have also a log like this:
Future<void> sendMessage() async {
var tokens = context.read<TokenProvider>();
if (messageController.text != "") {
globals.counter -= 1;
if(globals.counter == 0){AdManager.showIntAd();}
if (tokens.value != 0) {
decreaseTokens();
log(tokens.value.toString());
In Console it displays after every action 1 less. So the logic should work, but I am definitely missing something with the provider but honestly I have no clue what it could be.