Understanding Flutter routing: named routes, anonymous routes, and onGenerateRoute
Flutter routing is the process of navigating between screens or pages in a Flutter app. In this blog post, we’ll take a closer look at three important concepts related to routing in Flutter: named routes
, anonymous routes
, and onGenerateRoute
.
Named routes
In Flutter, named routes allow us to refer to screens by name, rather than having to reference them directly. To use named routes, we first need to define them in the routes
property of our MaterialApp
or CupertinoApp
widget. Here's an example:
MaterialApp(
routes: {
'/home': (context) => HomeScreen(),
'/about': (context) => AboutScreen(),
'/settings': (context) => SettingsScreen(),
},
// Other properties...
)
Once we’ve defined our named routes, we can navigate to them using the pushNamed
method. For example, to navigate to the AboutScreen
, we could use the following code:
Navigator.of(context).pushNamed('/about');
Named routes are particularly useful when working with deep linking, as they allow us to specify a unique URL for each screen in our app.
Anonymous routes
In Flutter, anonymous routes are routes that are not defined in the routes
property of our MaterialApp
or CupertinoApp
widget. Instead, they are created on the fly when we navigate to them using the push
method.
Here’s an example of using the push
method to navigate to an anonymous route:Copy code
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => MyScreen(),
),
);
Anonymous routes are useful when we want to create a temporary screen that is not part of our app’s main navigation flow. For example, we might use an anonymous route to display a modal dialog or a full-screen overlay.
onGenerateRoute
The onGenerateRoute
property of MaterialApp
and CupertinoApp
widgets allow us to customize the routing behavior of our app. This property takes a RouteFactory
function as its value, and this function is called whenever the app needs to create a Route
to handle a navigation request.
Here’s an example of using onGenerateRoute
to create a custom Route
for a named route:
MaterialApp(
onGenerateRoute: (settings) {
if (settings.name == '/custom') {
return MaterialPageRoute(
builder: (context) => CustomScreen(),
);
}
// Other routes...
},
// Other properties...
)
The RouteFactory
function receives a RouteSettings
object as its parameter, which contains information about the navigation request, such as the name of the route and any arguments that were passed to it. We can use this information to create a custom Route
that handles the navigation request in a specific way.
In summary, named routes, anonymous routes, and onGenerateRoute
are all important concepts to understand when working with routing in Flutter. Named routes allow us to refer to screens by name, and anonymous routes are created on-the-fly, and onGenerateRoute
allows us to customize the routing behavior of our app. Happy Coding 🎉