The smart way to handle routes in Flutter

I’m going to talk about the dynamic named route system in a flutter. only three-step you can manage your routing system.

Number one, make a constant file that keeps all the constant names of your Screen pages. See the image below I have four screens, I make a file that the name is routing_constants.dart. where declared my all-pages constant name.

Constant file

Number Two, Make another file that name is the router.dart, Where I put a function that name is generateRouter(), That return type is Route Dynamic. And also pass a parameter that type is RouteSettings see the image below.

Route type function

Now write your condition to route the screen see the below image

Route condition

Here i import a routing_constants.dart file. Look, here I create another page name ErrorPage(). If my condition didn’t get any match then it routes to ErrorPage(), Which's a simple Error handle from UI.

Number Three, Now config the function in MaterialApp look the below image

Here i imported router.dart file as router then look the MaterialApp take three parameters here, first one debugShowCheckedModeBanner I’m not talking about it. then onGenerateRoute take the router function that we created before in router.dart file. Then initialRoute take the first screen that we want to show here i import the SplashScreenRoute that i create a constant variable in routing_constants.dart.

Now The important thing is how we generate the route after the user action link button pressed. See below to Route a screen. Here RouteName is that we declaure in routing_constants.dart

Navigator.pushNamed(context, RouteName); 

Another one is sometimes we need to route screen and also need to clear back stack that time we need to use

Navigator.pushReplacementNamed(context, RouteName);

That’s for Today.

Thank you.

--

--

Software Maker

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store