Currently I'm working with two types of refs for reading a Riverpod provider: WidgetRef (inside build method, for rebuilding) and ProviderRef (anywhere outside of build method, in places unrelated to widget lifecycles).
I am also using auto_route package for routing and have made few route guards. This is my AppRouter so far:
@AutoRouterConfig()
class AppRouter extends _$AppRouter {
AppRouter(this.ref) : super();
WidgetRef ref;
@override
List<AutoRoute> get routes => [
AutoRoute(
page: OnboardingRoute.page,
guards: [OnboardingGuard(ref)],
// initial: true,
),
AutoRoute(
page: AuthRoute.page,
initial: true,
),
AutoRoute(
page: HomeRoute.page,
guards: [AuthGuard(ref)],
),
];
}
My app.dart:
class App extends ConsumerWidget {
const App({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final themeMode = ref.watch(themeRepositoryProvider).requireValue.themeMode;
return MaterialApp.router(
routerConfig: AppRouter(ref).config(),
themeMode: themeMode,
theme: appThemeData,
darkTheme: appThemeDataDark,
debugShowCheckedModeBanner: false,
);
}
}
My AuthGuard:
class AuthGuard extends AutoRouteGuard {
AuthGuard(this.ref) : super();
WidgetRef ref;
@override
void onNavigation(NavigationResolver resolver, StackRouter router) async {
final isLoggedIn = ref.watch(authProvider);
if (!isLoggedIn) {
router.push(AuthRoute(initial: AuthPages.login));
} else {
resolver.next(true);
}
}
}
The possible problem I'm currently facing: as you can see in the app.dart, I'm passing a WidgetRef to AppRouter through the constructor, which is then forwarded to the guards (AuthGuard and OnboardingGuard). This is done in order for me to read some provider's values, on top of which I do some conditional navigation in those route guards.
My question is, is it okay if I use WidgetRef here, or should I somehow inject ProviderRef to the AppRouter instead? Do you have any advices/negative feedback on this approach?
Thanks