Home > Back-end >  Access Riverpod 1 methods outside widget classes
Access Riverpod 1 methods outside widget classes

Time:04-18

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?

CodePudding user response:

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)
  • Related