flutterroutesstateflutter-go-routergorouter

How to cancel routing go_router in redirection?


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.


Solution

  • 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.