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.
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>[...],
);
}
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,
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With