1

Problem: I want to navigate to the shell route when a user is logged in and the login page when no one is logged in. What developers usually do is redirect the route to another one when user is logged in but I can't redirect the route to a shell route because I don't know how.

This is my router. I am using nested navigation to implement bottom navigation bar.

GoRouter router() {
  return GoRouter(
    debugLogDiagnostics: true,
    initialLocation: Routes.logIn.path,

    routes: _routes,
  );
}

List<RouteBase> get _routes => <RouteBase>[
      GoRoute(
        name: Routes.logIn.name,
        path: Routes.logIn.path,
        builder: (context, state) {
 
          return const LogInScreen();
        },
      
      ),
      ShellRoute(

        navigatorKey: _shellNavigatorKey,

        builder: (context, state, child) {
          return MainScreen(child: child);
        },
        routes: <RouteBase>[
          GoRoute(path: Routes.home.path,name: Routes.home.name,builder: (_,__) => const HomeScreen()),
          
        ]
      )
    ];


And this main file.

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
        builder: (_, __) => MaterialApp.router(
          routerConfig: router(),
          routeInformationParser: router().routeInformationParser,
          routerDelegate: router().routerDelegate,
          routeInformationProvider: router().routeInformationProvider,
          theme: AppTheme.lightTheme,
        ));
  }
}

1 Answers1

2

You can use the redirect attribute inside GoRouter to check the state of your user and redirect him to the appropriate route, like this:

GoRouter(
  ...
  routes: _routes,
  redirect: (BuildContext context, GoRouterState state) {
  //Replace this method depends on how you are managing your user's
  //Sign in status, then return the appropriate route you want to redirect to, 
  //make sure your login/authentication bloc is provided at the top level 
  //of your app
  if (AuthState.of(context).isSignedIn) {
    return Routes.home.path;
  } else {
    //else, remain at login page
    return null;
  }   
},)

More references at go_router's official API Reference: https://pub.dev/documentation/go_router/latest/topics/Redirection-topic.html

Lee Boon Kong
  • 1,007
  • 1
  • 8
  • 17
  • I can not get AuthState ? – karim mesghouni Apr 03 '23 at 20:51
  • 1
    The AuthState is managed by yourself, for example if your web backend is using a Bearer Token, the token will be saved locally using either SharedPreferences or Hive. Instead of using AuthState, you will be checking whether a token is present and valid from SharedPreferences. – Lee Boon Kong Apr 07 '23 at 08:20
  • @LeeBoonKong can you please share code snippet of same? Like on splashscreen we must redirect based on token..either to login screen or home screen – Hadi Khan Jul 08 '23 at 13:36