Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter: Riverpod change value using methods

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading