flutterguardriverpod

Ref Riverpod always null


I am using Riverpod for state management. I also use AutoRoute AuthGuard for protecting the route. So, I need to use the state to check if a user is logged in or not.

I don't know can I initialize Ref here.

Or any better choice?

Here is my code.

I want to use it inside the AuthGuard like this.

class AuthGuard extends AutoRouteGuard {
  final Ref? ref;

  @override
  void onNavigation(NavigationResolver resolver, StackRouter router) {

    ** //this ref is null and cause app crash.**
    if (ref.read(appProvider).isLoggedIn) {
      resolver.next(true);
    } else {
      Toastr.showWarning(text: 'Access Denied, please login to continue.');
      router.push(LoginRoute());
    }
  }
}

Solution

  • Use a consumer and pass its ref as parameter of your authguard

    _appRouter = AppRouter(authGuard: AuthGuard(ref: ref));