How to cancel routing go_router in redirection?

123 views Asked by At

How to cancel routing? If user is not premium user, Try to not allow to move to target routing. For example, like below.

redirect: (BuildContext context, GoRouterState state) {
  if (AuthState.of(context).isNotPremiumUser) {
   // cancel routing
  } else {
    return null;
  }   
},

How to do "return false" with go_router?

I did some research but nothing very conclusive.

2

There are 2 answers

1
Semih Ylmaz On BEST ANSWER

The only way i found is this.

redirect: (BuildContext context, GoRouterState state) {
  if (AuthState.of(context).isNotPremiumUser) {
   context.goNamed(state.matchedLocation)
  } else {
    return null;
  }   
},

This cancels the navigation because the BuildContext of Redirect do not have permission to navigate. It also gives us a log which can be problematic or not.

Assertion failed: inherited != null "No GoRouter found in context"

If you find this method problematic you also can navigate user to NavigationErrorScreen

redirect: (BuildContext context, GoRouterState state) {
  if (AuthState.of(context).isNotPremiumUser) {
    return '/navigation_error';
  } else {
    return null;
  }   
},

Navigation Error screen says You do not have permission or something and there must be a button for going back.

Navigating user same exact location can be tricky but i think it achievable with path_params or just calculate user state and navigate home/sign_in screen with that button.

1
Dhafin Rayhan On

In the redirect callback, the returned value will be the route that the router will redirect to. If the value is null, then it won't be redirected. To "cancel routing", you can return the current path (state.matchedLocation) as the redirecting target.

redirect: (BuildContext context, GoRouterState state) {
  if (AuthState.of(context).isNotPremiumUser) {
    return state.matchedLocation;
  } else {
    return null;
  }   
}