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:
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.
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.
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.
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 GetPageBuilder, ...