Equivalent of ChangeNotifierProvider widget in Riverpod

3,419

Riverpod has a ChangeNotifierProvider too, so you can use that.

As for the "I would like the provider to be automatically disposed when the page is popped", this functionality is instead implemented using autoDispose

So in the end, the syntax would be:

class MyNotifier extends ChangeNotifier {}

final myNotifierProvider = ChangeNotifierProvider.autoDispose<MyNotifier>((ref) {
  return MyNotifier();
});

...

class MyWidget extends ConsumerWidget {
  @override
  Widget build(BuildContext context, ScopedReader watch) {
    MyNotifier myNotifier = watch(myNotifierProvider);
  }
}

With this, when all the widgets using MyNotifier are destroyed (aka when the route is popped), then MyNotifier will be disposed.

Share:
3,419
Prince
Author by

Prince

Updated on December 25, 2022

Comments

  • Prince
    Prince over 1 year

    Is there a widget equivalent of the ChangeNotifierProvider widget of Provider in Riverpod?

    The use case is to create a provider only when a page whose parent widget is ChangeNotifierProvider/or a page that has ChangeNotifierProvider in its widget tree has been pushed unto the Navigator stack using create. I would like the provider to be automatically disposed when the page is popped and the ChangeNotifierProvider widget is removed from the widget tree just like in Provider.

  • Prince
    Prince over 3 years
    Thanks, it's actually right in the docs (riverpod.dev/docs/concepts/modifiers/auto_dispose). Still getting a hang of it 😔🤦‍♂️.
  • Wesley Barnes
    Wesley Barnes almost 3 years
    Ok, but ".when" doesnt work with a ChangeNotifierProvider, right?