I am using Getx on my sample project like this:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
initialRoute: AppLinks.LOGIN,
getPages: AppRoutes.pages,
initialBinding: MainBinding(),
);
}
}
I have this routes:
class AppRoutes {
static final pages = [
GetPage(
name: AppLinks.LOGIN,
page: () => Login(),
binding: LoginBinding(),
),
GetPage(
name: AppLinks.DASHBOARD,
page: () => Dashboard(),
middlewares: [
AuthGuard(),
],
children: [...
as you can see I declared a middelwares:
middlewares: [
AuthGuard(),
],
This is a simple midelware:
class AuthGuard extends GetMiddleware {
final authService = Get.find<AuthService>();
@override
int? get priority => 1;
@override
RouteSettings? redirect(String? route) {
if (authService.isAuthenticated)
return RouteSettings(name: AppLinks.LOGIN);
else
return RouteSettings(name: AppLinks.DASHBOARD);
}
}
Inside Loginpage I have a button:
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.red,
onPrimary: Colors.green,
onSurface: Colors.pink,
),
onPressed: () => controller.toDashboard(),
child: Text("Dashboard"),
)
and inside it’s controller I have this:
class LoginController extends GetxController {
toDashboard() => Get.toNamed(AppLinks.DASHBOARD);
}
But when I call toDashboard
method I get into loop in this statement:
@override
RouteSettings? redirect(String? route) {
if (authService.isAuthenticated)
return RouteSettings(name: AppLinks.LOGIN);
else
return RouteSettings(name: AppLinks.DASHBOARD);
}
}
I am using:
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
get: ^4.3.4
and doctor:
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.8.1, on Debian GNU/Linux 10 (buster) 4.19.0-18-amd64, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2020.3)
[✓] Android Studio
[✓] VS Code (version 1.63.2)
[✓] Connected device (2 available)
• No issues found!
3
Answers
Are you sure you want to send users to LoginPage if the user
isAuthenticated
?Or the opposite?
You need to change this:
to this:
No redirect needed if you are authenticated, see
https://github.com/jonataslaw/getx#redirect
No redirect needed if you are authenticated, see https://github.com/jonataslaw/getx#redirect
You need to change this:
to this: