Access Riverpod 1 methods outside widget classes

406

You probably don't want to use ProviderContainer directly unless you're mocking dependencies for your non-widget class when testing. Pass your non-widget class a Reader tear-off from a widget, e.g.

class YourObject {
   YourObject(this.reader);
   Reader? reader;

   void someFunc() {
      final dependency = reader?.call(someProvider);
   }
}

// Inside a consumer widget
final myObject = YourObject(ref.watch)
Share:
406
Amani Saaduddin
Author by

Amani Saaduddin

Updated on January 04, 2023

Comments

  • Amani Saaduddin
    Amani Saaduddin over 1 year

    How to access Riverpod ref from non-widget classes, before Riverpod 1, we could use context.read, where we had access to global navigation context. How can we achieve something similar in Riverpod 1? I've tried using a ProviderContainer and it's working, but need to wrap the MaterialApp with UncontrolledProviderScope to be able to access the container, this in turn prevents logging changes of StateNotifierProviders, which is very handy while debugging. Could anyone help with this?

  • Amani Saaduddin
    Amani Saaduddin about 2 years
    Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await initialize(); NotificationService().firebaseInitialization(); HttpOverrides.global = MyHttpOverrides(); SystemChrome.setPreferredOrientations([DeviceOrientation.por‌​traitUp]).then((_) { runApp(ProviderScope( observers: [Logger()], child: const MyApp(), )); }); } I need the ref in the NotficationService class, which I initialize in main where I don't have access to consumer widget.
  • Chris Wickens
    Chris Wickens about 2 years
    Then firebaseInitialization will need to be moved to a place where you have access to ref, such as in your MyApp widget.
  • D B
    D B over 1 year
    Undefined class 'Reader'.
  • Chris Wickens
    Chris Wickens over 1 year
    Sadly the previously recommended method has been deprecated and I'm not sure what the alternative is except to remove Riverpod from non-widget classes altogether. There's some further discussion here: github.com/rrousselGit/riverpod/discussions/1639