Search code examples
flutterauthenticationflutter-go-router

How to configure `go_router` redirect callback to let users use the app without logging in but when logged, redirect if accessing the login page?


Generic Description

I am developing an app in Flutter using go_router package. The auth logic is as follows:

  • the user is allowed to use the app without logging in
  • to access some features, the user must login
  • when user presses the login button (in login page), the router must invoke the redirect callback and send the user back to home, without me having to manually pop and push the login page.

Issue opened in Flutter GitHub repo

You can see the detailed situation in this link:

https://github.com/flutter/flutter/issues/147067


Solution

  • Inside the redirect callback, you can check the current auth state and the current path, and return the home route when the auth state is 'authenticated' and the current path is 'login'.

    For example:

    redirect: (_, state) {
      final authState = ... // Get auth state based on your auth/state management strategy
      final currentPath = state.fullPath; // There are other options, such as `state.matchedLocation` and `state.name`
      
      if (authState == AuthState.authenticated && currentPath == '/login') {
        return '/home';
      }
    }
    

    Additionally, you have to make sure that you navigate to the login screen with the context.go method, as context.push won't change the current location, which causes the state would still be in the previous route (in this case, the home route).

    Change

    context.push('/login')
    

    to

    context.go('/login')
    

    The package has an official example that implements this behavior:

    I also made an example with a slightly different approach to simplify the logic: