tezvyn:

Flutter's onGenerateRoute for Dynamic Routes

AI-drafted, machine-checkedSource: api.flutter.devintermediate

onGenerateRoute is Flutter's central switchboard for creating routes on the fly, especially when they need data. Use it to pass arguments to new screens or handle routes not statically defined in the `routes` map.

WHY IT EXISTS Apps often need more than static, pre-defined routes. You might need to navigate to a user profile using an ID like '/profile/123' or pass complex objects to a new screen. onGenerateRoute provides a centralized, dynamic way to handle these cases, intercepting route requests and building the correct screen with the necessary data.

THE MENTAL MODEL Think of onGenerateRoute as a factory function for your app's pages. When Navigator.pushNamed('/some/route', arguments: ...) is called, Flutter first checks its static routes map. If the route isn't there, it knocks on onGenerateRoute's door and says, "Build me a page for '/some/route' with these arguments." Your function is then responsible for returning a valid Route object.

HOW IT WORKS You assign a function to the onGenerateRoute property of your MaterialApp. This function receives a RouteSettings object, which contains the name of the route being requested and any arguments passed to it. Inside your function, you typically use a switch statement on settings.name. For each case, you instantiate the corresponding widget, wrap it in a MaterialPageRoute, and return it.

WHEN TO USE IT Use onGenerateRoute whenever you need to pass data to a new route during navigation or handle dynamic route paths (e.g., '/user/123'). It keeps your routing logic clean and centralized. It is called only for named routes that are not found in the routes map.

WHEN NOT TO USE IT For simple apps with a small, fixed set of pages that don't require arguments, the static routes map is simpler. If you only need a catch-all for routes that don't match anything else (a 404 page), use onUnknownRoute, which runs after onGenerateRoute fails to produce a route.

ONE CANONICAL EXAMPLE In your MaterialApp, you define onGenerateRoute. When a user taps an item, you call Navigator.pushNamed(context, '/item/3'). Your onGenerateRoute function receives the RouteSettings with name: '/item/3'. You can then parse the ID '3' from the name, construct an ItemDetailsPage with the correct data, and return it inside a MaterialPageRoute.

Read the original → api.flutter.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.