Flutter Riverpod Widget Ref access outside of the widget

Created At: 2023-08-17 22:59:14 Updated At: 2023-08-17 23:47:58

Riverpod WidgetRef ref object comes with many handy properties that are useful for accessing the providers and related context.

But passing WidgetRef ref object in constructor dependencies is not a good. Official document does not recommend passing the ref object like.

They say it's 

dangerous to pass the ref object with it. 

The reason it's dangerous that every WidgetRef object is related to a Widget object. Since ref object is associated with a Widget, then if we pass to a controller directly, it creates a misuse of the object. In fact any one can use it. And this may cause null issue or wrong context.

To understand why, consider that this: passing WidgetRef is a bad idea because WidgetRefs are (indeed) linked their Widget's element. Their life cycle are indeed tied to the life cycle of a widget, whereas the lifecycle of a provider is a different thing. In a certain way, WidgetRef is closer to an AutoDisposeRef.

Pass safely

If you really need to pass the WidgetRef ref object, then you may pass it to function from a Widget. 

The appButton widget is inside Center widget and Center widget is inside ConsumerStatefulWidget. So we can access the ref object here. 

And this ref object is particularly tied to current app widget and that's very specific. Since it's very specific we can pass it to another function as WidgetRef object.

Thus accessing WidgetRef is much safer now. See how the creator of Riverpod says about it.

Comment

Add Reviews