I'm trying to learn how to use riverpod for state management in a Flutter app. I'm building a simple counter app and I have done the following:
My provider:
@riverpod
class Counter extends _$Counter {
int _value = 0;
@override
int build() => _value;
void increment() {
print("incrementing");
_value++;
}
}
In my ConsumerWidget
build method I'm obtaining the following:
final counterValue = ref.watch(counterProvider);
final counter = ref.read(counterProvider.notifier);
I present the value in a Text widget in the following manner:
Text(counterValue.toString())
And my button action is the following:
onPressed: () {
counter.increment();
}
In my console I see it's printing "incrementing" meaning that my method is called. But the value on screen doesn't seem to change.
What am I missing?
You're changing a property of the notifier. The notifier emits only when its state is updated. If your incrementor was updating with state++
, it would work, and you wouldn't need the _value
property at all.