Conditionally loading a Flutter App’s first screen with AutoRoute and Navigator 2.0
This is just a small blog to help you understand how easy it is to conditionally navigate to a page on app launch with auto-route.
I’m assuming you already have auto router setup. If not, check this link to see how to set it up with navigator 2.0 in Flutter.
If you have setup everything, your root widget’s build method would look something like this:
_appRouteris initialised before the
final _appRouter = AppRouter();
- I also have some booleans being fetched from hive at run-time, in the
late bool isSignedIn, isVerified, isTnCAccepted;
The code-snippet of importance is this:
if (!isSignedIn) LandingScreen(),
if (isSignedIn && !isTnCAccepted) PledgeScreen(),
if (isSignedIn && isTnCAccepted) DashboardScreen(),
So, basically we can provide any screens/routes conditionally to the
initialRoutes prop in
_appRouter.delegate, which is used to setup the
routerDelegate for our
In my case, if the user is not signed in, it returns LandingScreen. If the user is signed in and has not accepted the terms, it takes them to the PledgeScreen, else, it takes them to the DashboardScreen.
Full Code example
LandingScreen come from the file of routes generated by
auto_router (it might be router.gr.dart for you, check auto_router documentation for reference) .
These are my routes:
This is how easy it was to use AutoRouter with Navigator2.0, when you have to conditionally open a page in the app. In addition to this, AutoRouter also simplifies deep-links, opening the correct page on launch with dynamic links etc. Will be covering that soon! Hope you liked my first blog here :). Would love to hear suggestions to improve.