I'm in the process of migrating my app to use flutter_riverpod
package. At the moment, my app is using provider
package to manage/deal with app state.
I have a lot of static methods inside multiple utility classes that take a BuildContext
as input. I use the context to access the provider, which allows me to read and modify the state:
// This relies on the provider package
abstract class SomeRandomUtilityClass {
static FutureOr<String?> redirect(BuildContext context) {
bool isSignedIn = context.read<AuthProvider>().isSignedIn;
if (!isSignedIn) {
return '/signIn';
} else {
return null;
}
}
How do I achieve this with Riverpod? From what I understand, you need a Ref
to be able to read/write from/to a provider, but I'm not even sure if the APIs allow it.
I tried replacing the BuildContext
parameters of my methods with a Ref
object, but I'm having trouble getting one. All I can access is a WidgetRef
:
class App extends ConsumerWidget {
/** ... **/
@override
Widget build(BuildContext context, WidgetRef ref) {
return MaterialApp.router(
/** ... **/
routerConfig: GoRouter(
/** ... **/
routes: [
GoRoute(
/** ... **/
// This doesn't work, because the method I'm calling expects a Ref,
// and not a WidgetRef.
redirect: (_, __) => SomeRandomUtilityClass.redirect(ref),
),
],
),
);
}
}
An easy fix would be to modify my static methods by changing the type of the parameter from Ref
to WidgetRef
, but the maintainer of the Riverpod package says that passing WidgetRef
s is a bad idea.
I might be misunderstanding something. Please let me know if I am.