Sras
Sras

Reputation: 2294

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());
    }
  }
}

Upvotes: 2

Views: 627

Answers (2)

Kydav
Kydav

Reputation: 31

If you update AutoRoute to latest you might run into some problems with this implementation. I had a previous app where I was using an earlier version of AutoRoute and you can pass a type for a routeguard. However, with the latest, since v6 of AutoRoute, the router config is different. You can access ref inside of a RouteGuard, but then when you instantiate the router you have to pass the routeguard with widgetRef.

So your router declaration:

final appRouter = Router(AuthRouteGuard(ref: ref));

Then your router config will look like:

Router extends _$Router {
 Router(this.authRouteGuard);
 final AuthRouteGuard authRouteGuard;

Then you will need to late initialize your routes to set the guard to authRouteGuard.

late List<AutoRoute> routes = [AutoRoute(...guards:[authRouteGuard])];

This is where I discovered my solution was a closed issue on the AutoRoute Repo: https://github.com/Milad-Akarie/auto_route_library/issues/1469

Upvotes: 1

Sras
Sras

Reputation: 2294

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

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

Upvotes: 1

Related Questions