Search code examples
androidiosflutterdartriverpod

How can we access provider without ref object in flutter_riverpod?


Suppose you are trying to manipulate a provider at some place where you don't have access to a WidgetRef object.

Usually we access a provider like this, final yourProvider = ref.read('your_provider');

Can we manipulate the provider state without the ref object here.

As in Getx we, being at any place can access the controller with,

YourGetXController controller = Get.find();
controller.value = newValue;

Tried few solutions from internet and chatGPT but not being able to figure out how. Tring if it can be done with flutter_riverpod, because the app is built with flutter_riverpod. I need the above mentioned scenario to work at one particular place. If I don't find a solution I'll use GetX for this particular scenario.


Solution

  • GetX - it's a variation on the architecture of how not to do it. In this case, there is no way you can externally access the provider state without using ref. All you can do is:

    1. Pass Ref as an argument to a function where inside will require access to the provider. (bad pattern)
    2. Use ProviderScope.containerOf(context) to get a reference to the current ProviderContainer where it is possible to read the provider value
    3. Use a class the Notifier class, where ref is available as a getter inside the class.

    In any case, if you have access to data as global variables, it will soon turn into a terrible mess of untraceable code.