how can i redirect correctly to routes ?
My application has to have some route security and I try to do it with GoRouter but it always executes one more redirection and always returns to home.
There are only 3 secure routes (profile, order, favorites) and if you are not logged in you must go back to login.
But when I put any of the 3 routes in the url, it redirects me to the login and immediately to the home (this is what should not happen)
Can somebody help me? I changed the logic several times but I always come back to the same point.
class AppRouter {
final SessionCubit sessionCubit;
GoRouter get router => _goRouter;
AppRouter(this.sessionCubit);
late final GoRouter _goRouter = GoRouter(
refreshListenable: GoRouterRefreshStream(sessionCubit.stream),
initialLocation: APP_PAGE.home.toPath,
routes: <GoRoute>[
GoRoute(
path: APP_PAGE.home.toPath,
name: APP_PAGE.home.toName,
builder: (context, state) => MyHomePage(),
),
GoRoute(
path: APP_PAGE.login.toPath,
name: APP_PAGE.login.toName,
builder: (context, state) => const LoginPage(),
),
GoRoute(
path: APP_PAGE.profile.toPath,
name: APP_PAGE.profile.toName,
builder: (context, state) => MyProfile(),
),
GoRoute(
path: APP_PAGE.page1.toPath,
name: APP_PAGE.page1.toName,
builder: (context, state) => const Page1(),
),
GoRoute(
path: APP_PAGE.error.toPath,
name: APP_PAGE.error.toName,
builder: (context, state) => ErrorPage(error: state.extra.toString()),
),
GoRoute(
path: APP_PAGE.page2.toPath,
name: APP_PAGE.page2.toName,
builder: (context, state) => const Page2(),
),
],
debugLogDiagnostics: true,
errorBuilder: (context, state) => ErrorPage(error: state.error.toString()),
redirect: (context, state) {
final userAutheticated = sessionCubit.state is Authenticated;
if (userAutheticated) {
if (state.subloc == '/login') return '/home';
if (state.subloc == '/profile') return '/profile';
if (state.subloc.contains('/page1')) return '/page1';
return '/home';
} else {
if (state.subloc == '/home') {
return '/home';
}
if (state.subloc == '/page2') {
return '/page2';
} else {
return '/login';
}
}
},
);
}
UPDATE 05/11 I find the solution.
First -> use the last version of go_router 5.1.5 (the redirect issue is on the older versions).
Second -> I modify the redirect logic:
if(!userAutheticated && !onloginPage && !onpublicPage1 && !onPublicPage2 && !onPublicPageN){
return '/login';
}
if (userAutheticated && onloginPage) {
return '/home';
}
//you must include this. so if condition not meet, there is no redirect
return null;
Note: I don't know why flutter web debug mode doesn't work properly. So I run the project on release mode and Voilá, it's works!.
Thanks So Much for the help!!!