Riverpod base class for WidgetRef and ProviderRef

532

Apparently it's been answered in here by the creator https://github.com/rrousselGit/riverpod/discussions/1152

However, I wondered why Ref and WidgetRef don't share a common interface?

That's voluntary. The fact that you need a common interface shows a flaw in your architecture

You most definitely did something wrong somewhere. You should never need to use WidgetRef outside of widgets

So, there is no base class or common interface. It's considered there is flaw in your code if you need WidgetRef outside of widgets.

[Edit] Btw there is a way to share a function that works with both ref. By setting it parameters with notifier class (to change state), or just set the object (to read).

function(
  ANotifierClass noti, 
  AClass a,
) {
  noti.callSomething();
  // Do something with a
}

called like

// ref can be WidgetRef or Ref
function(
  ref.read(aProvider.notifier),
  ref.read(aProvider),
);
Share:
532
Ryde
Author by

Ryde

Updated on January 04, 2023

Comments

  • Ryde
    Ryde over 1 year
    function(
      WidgetRef ref, 
      // ProviderRef ref,
    ) {
      final a = ref.read(aProvider);
      // Some logic
    }
    

    What base class that can read WidgetRef and ProviderRef?

    • Josteve
      Josteve about 2 years
      There's a Ref class.
    • Ryde
      Ryde about 2 years
      @Josteve could you make it as answer, I will tick it.
    • Ryde
      Ryde about 2 years
      wait I have this error The argument type 'WidgetRef' can't be assigned to the parameter type 'Ref'
    • Josteve
      Josteve about 2 years
      Hi @Ryde, please share the code.