Home > Back-end >  How to redirect current page to another using Flutter's go_router?
How to redirect current page to another using Flutter's go_router?

Time:06-27

How can I achieve the same effect as the Navigator.pushReplacement does, but in declarative routing with go_router?

Explained

I have 3 pages: /loading, /login, /. And logic is (pseudocode):

/loading {
 performSomeComputation();
 if checkAuthorization() == authorized {
   go /;
 } else {
   go /login;
 }
}

/login {
  waitForUserToLogIn();
  go /;
}

/ {
 // account logic
}

CodePudding user response:

With go_router you can either use .go() or .push().

.push() pushes a new page onto the stack.

.go() works with sub-routes. Every top-level route has got its own stack. Here is a short example:

final GoRouter _router = GoRouter(
    routes: <GoRoute>[
      GoRoute(
        path: '/',
        builder: (BuildContext context, GoRouterState state) =>
            const Page1Screen(),
        routes: [
          GoRoute(
            path: 'page2',
            builder: (BuildContext context, GoRouterState state) =>
            const Page2Screen(),          ),
        ],
      ),
      GoRoute(
        path: '/page3',
        builder: (BuildContext context, GoRouterState state) =>
        const Page3Screen(),
      ),
    ],
  );
  • If you go from the top-level route '/' to the subroute '/page2', '/page2' will be added to the '/' stack. You'll get the back button in the app bar because both '/' and '/page2' are on the stack of top-level route '/'.
  • If you go from the top-level route '/' to '/page3', you replace the current '/' stack with the '/page3' stack because '/page3' is also a top-level route. You will not see a back button because '/page3' is the first page on the stack of top-level route '/page3'.

What you might be looking for though is redirect. You can pass a redirect function to the GoRouter constructor if you want to redirect on state changes like login and logout. You can combine this with state management libraries like Bloc. You can pass a refreshListenable to the GoRouter constructor that triggers a refresh of the route every time the state stream (yourBloc.stream) changes.

go_router also got a great documentation: https://gorouter.dev/

  • Related