GoRouter - Web - How to detect that the user entered an URL in the browser's address bar?

Viewed 66

I'm using go_router on web and I would like to implement a different redirect logic between the call of the go_router's API (push, go, replace) and when the user enters an URL in the browser address bar.

I didn't find any solution and I was going to implement it this way:

If I understood correctly, when the user enters an URL in the browser address bar, it restarts the application from scratch, while calling the API doesn't. And I came to this:

bool _isFirstRedirect = true;

GoRouter(
  routes: myRoutes,
  redirect: (state) {
    if (_isFirstRedirect) {
      // Logic when the user enters an URL in the browser's address bar.
      _isFirstRedirect = false;
    } else {
      // Logic when it comes from a call of the go_router's API.
    }
  }, 
);

But I'm not sure that is a good design. Is there a better way to do that?

1 Answers

Use initialLocation in GoRouter constructor. Something like this:

GoRouter(
  initialLocation: '/page3',
  routes: [
    GoRoute(
      path: '/',
      builder: (context, state) => const Page1Screen(),
    ),
    GoRoute(
      path: '/page2',
      builder: (context, state) => const Page2Screen(),
    ),
    GoRoute(
      path: '/page3',
      builder: (context, state) => const Page3Screen(),
    ),
  ],
);
Related