Member-only story
Flutter Fast, Flutter Far — Issue #4
Hey! Don’t go there! An intro to Route Guards in Flutter
Navigation in a mobile app is a bit more involved than pushing a route here and popping a route there. Some routes should only be viewed by a user who is authenticated while others are available to the public. Some routes will only behave and display properly if the user has an active internet connection while others show static assets that never change.
Is it possible to verify these requirements are met before loading each new route? With Route Guards, anything is possible.
Route Guards
Route Guards were first introduced in the Angular programming language as interfaces used to control the accessibility of a route based on a given condition. This Angular feature set included methods for monitoring forward and backward navigation, as well as processing the data that was sent from one route to another. As the name indicates, guards would sit between routes and determine if navigation between the two was allowed.
The problem is that Flutter doesn’t provide built-in support for guards so a lot of the navigation-validation-leg-work has to be done inside your route code. For example, you can perform a check in the initialization method of your route to determine if the route should actually be rendered. Or, you could wrap your view in a FutureBuilder and perform your check there. Either way, you would still be pushing the requested route onto your navigation stack which is not ideal.