Search code examples
androidflutterflutter-go-router

GoRouter redirect parameter allows going back to home page


In my Flutter app for Android, at opening, I want to force the user to log-in. I use the GoRouter redirect parameter:

final router = GoRouter(
    routes: [
      GoRoute(
        path: '/',
        builder: (context, state) {
          return const HomePage();
        },
      routes: [
        GoRoute(
          path: 'login',
          builder: (context, state) {
            return const LogIn();
          }
        )],
    redirect: ((context, state) {
      if (!userLoggedIn) {
        return '/login';
      }
      return null;
    })

It works: if userLoggedIn, that checks Firebase current user state, is false, the app opens at login page. But clicking on Android back button the app navigates to home page. How can i avoid it? I want the app closes on clicking back button.

I tried also initialLocation parameter instead of redirect parameter but can't get the solution.


Solution

  • I have found the solution: the two GoRoutes must be at the same level. 'login' can't be nested in '/':

    final router = GoRouter(
      routes: [
        GoRoute(
          path: '/',
          builder: (context, state) {
            return const HomePage();
          },
        ),
        GoRoute(
          path: 'login',
          builder: (context, state) {
            return const LogIn();
          },
        ),
      ],
      redirect: ((context, state) {
        if (!userLoggedIn) {
          return '/login';
        }
        return null;
      })