tezvyn:

Flutter Named Routes: Navigate with Strings, Not Widgets

AI-drafted, machine-checkedSource: docs.flutter.devbeginner

Think of named routes as URL paths for your app's screens. Instead of building a screen widget on the spot, you just tell Flutter "go to '/profile'". This is ideal for centralizing navigation in large apps and for enabling deep linking.

WHY IT EXISTS In a growing Flutter app, navigation can become scattered. Pushing MaterialPageRoute instances directly from buttons couples your UI tightly to your navigation logic. This makes it hard to refactor, difficult to get a high-level view of your app's structure, and complicates features like deep linking.

THE MENTAL MODEL Treat your app's screens like web pages with unique addresses. Instead of telling a button how to build the next page, you just give it the address (the route name). A central "router" in your app looks up that address and builds the correct page. You're moving from imperative navigation ("build and push this widget") to a more declarative style ("go to this named location").

HOW IT WORKS You define a map of routes in your top-level MaterialApp widget. The map's keys are string names (e.g., '/' or '/settings'), and the values are builder functions that return the screen widget for that route. To navigate, you call Navigator.pushNamed(context, '/settings'). The navigator finds the matching string in your routes map and pushes the corresponding widget onto the navigation stack. For passing data or handling dynamic routes, you can use the onGenerateRoute callback.

WHEN TO USE IT Use named routes in any app with more than a handful of screens to keep navigation logic clean and centralized. It's almost mandatory if you need to implement deep linking, allowing external URLs or push notifications to open specific screens. It creates a self-documenting sitemap of your app.

WHEN NOT TO USE IT For a very simple app with only two or three screens, the setup can be overkill; a direct Navigator.push is simpler. Also, the basic named routes system can become clumsy for highly complex navigation flows with lots of conditional logic; a dedicated routing package like go_router might be a better choice in those cases.

ONE CANONICAL EXAMPLE In your main.dart, you configure your MaterialApp with an initialRoute and a routes map. For example: MaterialApp(initialRoute: '/', routes: { '/': (context) => HomeScreen(), '/details': (context) => DetailsScreen(), }). Then, from a button's onPressed callback anywhere in the app, you can navigate by calling Navigator.pushNamed(context, '/details');.

Read the original → docs.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.