1

I am new to using RiverPod. previously I used Provider for state management.

in case of provider I could use a provider outside widget tree to get value using syntax

Provider.of<MyModel>(context,listen:true).someFunction();

how do I do the same in RiverPod? for now I am using Consumer Builder and Consumer Widget. I was wondering if there's a way to call a riverpod provider without using Consumer.

Junaid Tariq
  • 568
  • 8
  • 22

2 Answers2

3

You can easily call riverpord provider without using Consumer. Please check out my below extension which is very helpful to call the provider based on context where it will work for the read function without any consumer or consumer widget.

extension Context on BuildContext {
  // Custom call a provider for reading method only
  // It will be helpful for us for calling the read function
  // without Consumer,ConsumerWidget or ConsumerStatefulWidget
  // Incase if you face any issue using this then please wrap your widget
  // with consumer and then call your provider

  T read<T>(ProviderBase<T> provider) {
     return ProviderScope.containerOf(this, listen: false).read(provider);
  }
}

After then under the build method, you must call context.read(yourProviderName)

lepsch
  • 8,927
  • 5
  • 24
  • 44
Abu Sayed
  • 86
  • 4
1

let's say you have a separate class that is responsible for ui logic:

class UiController {
  UiController(this._ref);

  final Ref _ref;

  Reader get _reader => _ref.read;

  static final pr = Provider<UiController>((ref) => UiController(ref));

  void someFunction() {
    _reader(otherProvider).getValue();
  }
}

from a widget or other functions where ref is accessed, you can call:

ref.read(UiController.pr).someFunction();
Ruble
  • 2,589
  • 3
  • 6
  • 29
  • can't ref.read(UiController.pr).someFunction(); be called somewhere outside a widget class? – Junaid Tariq Sep 05 '22 at 07:21
  • only if we have access to ref. Otherwise, you can try using [UncontrolledProviderScope](https://github.com/rrousselGit/riverpod/issues/295#issuecomment-770368500) – Ruble Sep 05 '22 at 09:51