auto_route is displaying the initialRoute every time I perform a hot reload or reload my Flutter project

212 Views Asked by At

I just started using auto_route to handle routing in my Flutter app, but now, whenever I save in VSCode and trigger hot reload, it displays the initialRoute again. The expected behavior should be to stay on the current route unless I perform a hot restart. This only happens when I use auto_route; if I don't use this package, I get the correct behavior upon saving. Does anyone know if I can avoid this behavior and still use this package?

I tried to not mark any route as initial but then I just get a blank screen.

2

There are 2 best solutions below

0
Dann On

You have to ensure that you are not creating an instance of the AppRoute in the build method such as;

final router = AppRouter()

This will recreate the router on rebuilds. You can use a service locator like GetIt or Riverpod to pass in a single instance of the router AppRouter

0
feraj_ official On

You have to create your instance just outside the build method and it's work perfectly.

note: I don't know it's an optimise solution or not , but I just fix the same issue by doing this little change.

class MyApp extends StatelessWidget {
  MyApp({super.key});

  final appRouter = AppRouter();

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: appRouter.config(),
      theme: ThemeData.light(), 
      darkTheme: ThemeData.dark(),
    );
  }
}