Conditionally loading a Flutter App’s first screen with AutoRoute and Navigator 2.0

Siddhartha Varma
2 min readJun 17, 2021

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.

Introduction

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:

Build method in root widget with auto_route and navigator 2.0

For context:

  • Here _appRouter is initialised before the initState function:
final _appRouter = AppRouter();
  • I also have some booleans being fetched from hive at run-time, in the initState method:
late bool isSignedIn, isVerified, isTnCAccepted;

The code-snippet of importance is this:

routerDelegate: _appRouter.delegate(
initialRoutes: [
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 MaterialApp.

Explanation

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

Here PledgeScreen and 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:

Conclusion

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.

--

--