Error when navigating with AppRoute Flutter

43 Views Asked by At

I use auto_route and I have a problem with routing when I open app I get error (attached image below). I need it to check when opening application if the user is authorized and then push it to MainRoute.page.

AppRouter

class AppRouter extends _$AppRouter {
  @override
  List<AutoRoute> get routes => [
        AutoRoute(
          page: AuthRoute.page,
          path: '/',
          initial: true,
          guards: [AuthGuard()],
        ),
        AutoRoute(
          page: MainRoute.page,
          children: [
            AutoRoute(path: 'dashboard', page: DashboardRoute.page),
            AutoRoute(path: 'crypto-list', page: CryptoListRoute.page),
            AutoRoute(path: 'settings', page: SettingsRoute.page),
          ],
        ),
        AutoRoute(page: CoinDetailsRoute.page, path: '/coin-details'),
      ];
}

AutoRouteGuard

class AuthGuard extends AutoRouteGuard {
  @override
  void onNavigation(NavigationResolver resolver, StackRouter router) async {
    final AuthProvider appState = AuthProvider();

    if (appState.isLoggedIn) {
      resolver.next();
    } else {
      router.push(const AuthRoute());
    }
  }
}

main

return MaterialApp.router(
      theme: darkTheme,
      routerConfig: _appRouter.config(
        navigatorObservers: () => [
          TalkerRouteObserver(
            GetIt.I<Talker>(),
          ),
        ],
      ),
      title: 'Flutter Demo',
    );

login screen

void onPressedMethod(bool isRegister) {
    if (isRegister) {
      AutoRouter.of(context).push(
        const MainRoute(),
      );
    } else {
      AutoRouter.of(context).push(
        const MainRoute(),
      );
    }
  }

error

enter image description here

1

There are 1 best solutions below

3
Vladimir Gadzhov On

Your issue is that when user is not authenticated you are returning it back to the AuthRoute, which has Route Guard and the process repeat until you receive a StackOverflow Exception.

Please consider remove the guard on the AuthRoute

class AppRouter extends _$AppRouter {
  @override
  List<AutoRoute> get routes => [
        AutoRoute(
          page: AuthRoute.page,
          path: '/',
          initial: true,
          //guards: [AuthGuard()], // <------ remove it
        ),
        AutoRoute(
          page: MainRoute.page,
          children: [
            AutoRoute(path: 'dashboard', page: DashboardRoute.page),
            AutoRoute(path: 'crypto-list', page: CryptoListRoute.page),
            AutoRoute(path: 'settings', page: SettingsRoute.page),
          ],
        ),
        AutoRoute(page: CoinDetailsRoute.page, path: '/coin-details'),
      ];
}