Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unknown behavior with hot reload when using the go_router package

I was using go_router in a project. I had a separate file with an instance of GoRouter with all the routes (home, login, register). Then, I added authentication with a cubit. So I had to modify my GoRouter instance to a function that received with auth cubit and use it to redirect to the appropriate route.

Everything seemed alright but then I realized something. For example, if I was in the login route and push register to the stack and modify the register page and save the file, the hot reload would take me back to login. So every time I want to make some changes to the register page, I would go back to the login route and then manually go back to the register to see my changes.

Here is an example:

Demo app

PS: I just started using the go_router package so maybe I am doing something incorrectly.

like image 641
Miguel Yurivilca Avatar asked Dec 30 '25 21:12

Miguel Yurivilca


2 Answers

The solution is simple


GoRouter store state of your routes. If you create new instance of GoRouter then it lose state and navigate you to initial route.

To solve this problem I create Instance of GoRouter and store it as Singleton or as Global instance.

class AuthNavigation {

  static const String settings = '/';
  static const String myFriends = '/my_friends';
  
  
  final GoRouter goRouter; // This instance will be store route state
  
  AuthNavigation() : goRouter = _router;

  static GoRouter get _router => GoRouter(
        routes: <GoRoute>[...],
      );
      
}
like image 148
Yerkebulan Duisebay Avatar answered Jan 01 '26 15:01

Yerkebulan Duisebay


Simply mark your router as static, so that it uses the same instance when you initialize it everytime in MaterialApp.router()

class AppRouter {
  static final GoRouter _router = GoRouter(
    routes: [
      GoRoute(
        path: "/",
        builder: (context, state) => const HomeScreen(),
      ),
    ],
  );

  GoRouter get router => _router;
}

And, In MaterialApp.router():

MaterialApp.router(
   routerDelegate: AppRouter().router.routerDelegate,
   routeInformationProvider: AppRouter().router.routeInformationProvider,
   routeInformationParser: AppRouter().router.routeInformationParser,
 )
like image 37
Dinesh Bala Avatar answered Jan 01 '26 15:01

Dinesh Bala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!