Route guard is very use full to avoid multiple logic test. Imagine some pages that require authenticated users and some not.
So you will need to deal with the evaluating if you can proceed with routing every time.
A route guard can be configured as a named routes parameter. it evaluates if the user can access the page he is requesting and let the routing proceed or redirect to another page if not.
An alternative could be a beforRoutingCallback (current routing callback is fired after the routing)
That I'm looking for https://github.com/jonataslaw/getx/issues/392
+1 for something like beforeRoutingCallback.
I understand the concerns and showing a NotAuthorized page is better as a body, but for web, one place to check Auth is a very valid option. All JS frameworks have something similar that you can change the route. In my app only 1% of the screens are "anonymous" all others are protected. Off course we can create something ourself, a wrapper function around the GetPage, but a beforeRoutingCallback that returns null (= go ahead and execute the GetPage, or a Page widget if you want a new one, Login for example). @jonataslaw
Can anyone suggest a work around for now please
Have a look at this which protects your whole app. https://github.com/jonataslaw/getx/issues/223
I need to protected selective screens .
Here is my workaround for now: Wrap wrap GetPage into a function that will handle RouteGuard logic :
typedef Widget RouteGuard(Widget target);
Widget loginGuard(Widget target) {
// Handle redirect or return the targeted Widget
// e.i: if (Find.auth.uid == null) return LoginPage();
return target;
}
// Passed to GetPage page field to be called each time we try to navigate. We cass pass multiple route guard as list
Widget _redirect(Widget target, [List<RouteGuard> guards = const []]) {
Widget _result = target;
guards.forEach((element) => _result = element(_result));
return _result;
}
// Helper for GetPage creation
GetPage _createPage(String name, Widget target, [List<RouteGuard> guards = const []]) {
return GetPage(
name: name,
page: () => _redirect(target, guards),
);
}
// Pages definition
final pages = [
_createPage(Routes.startup, StartupPage()),
_createPage(Routes.home, HomePage(), [loginGuard]),
];
I think this is implemeted now
GetMiddleware
Looks for https://github.com/jonataslaw/getx#redirect
As this has already been implemented, I am closing
Most helpful comment
Here is my workaround for now: Wrap wrap GetPage into a function that will handle RouteGuard logic :