Middleware
Learn to intercept the navigation process with the help of middleware.
What is middleware?
Middleware is a layer of callbacks that we can add to a route to intercept the navigation process. Using these callbacks, we can add checks, write custom logic, and modify various stages of the process. This gives us fine-grained control over the whole navigation flow.
Start by extending the GetMiddleware
class:
class SettingsMiddleware extends GetMiddleware {}
Next, we override the methods in this class to perform actions at different stages.
The onPageCalled
method
onPageCalled
is triggered the moment the page is called by the navigation system, hence the name. We get access to the actual page that’s mapped to the route.
@overrideGetPage? onPageCalled(GetPage? page) {// Get user data.final user = getUserData();// Check if data is available.if (user != null) {// Add the user's name to the page arguments.return page?.copy(arguments: {'name': user.name},);}return super.onPageCalled(page);}
In the example above, we’re first fetching the user data. If the data is present, we add the user’s name to the page’s arguments
. This way, we can modify the page however we like, before navigating to it.
The redirect
method
We get the option to redirect to an entirely new page using the redirect
method. We get access to the route’s name and the function returns the relevant RouteSettings
.
@overrideRouteSettings? redirect(String? route) {// If the user is logged in, do not redirect.if (loggedIn) {return null;} else {// Else, redirect to the login page.return RouteSettings(name: '/login');}}
If we want to prevent redirecting, we return null
. That’s the default behavior as well. In the example above, we check if the user is logged in or not. In case they aren’t, we redirect to the login page.
The onBindingsStart
method
Bindings are classes that contain the dependencies corresponding to a particular page. When a page is being navigated to, the dependencies in its bindings are initialized before the page is constructed. We can perform an action right before their initialization in the onBindingsStart
method.
It takes in a list of bindings and expects a list in return as well.
@overrideList<Bindings>? onBindingsStart(List<Bindings>? bindings) {// Whether to grant admin access to the user.if (allowAdminAccess) {// Add [AdminBinding] to the list of bindings associated with the route.bindings?.add(AdminBinding());}return bindings;}
The code above shows how we can add an additional AdminBinding
to the bindings list if we wish to give this route admin privileges.
The onPageBuildStart
method
Once the bindings are initialized and page is about to be constructed, onPageBuildStart
method is called. It takes in and spits out ...