Named routes help you move between screens easily by giving each screen a simple name. This makes your app navigation clear and organized.
0
0
Named routes in Flutter
Introduction
When your app has multiple screens and you want to switch between them clearly.
When you want to avoid writing long code to open new screens.
When you want to keep your navigation code clean and easy to read.
When you want to reuse screen names to navigate from different parts of your app.
Syntax
Flutter
MaterialApp( initialRoute: '/home', routes: { '/home': (context) => HomeScreen(), '/settings': (context) => SettingsScreen(), }, )
initialRoute sets the first screen shown when the app starts.
routes is a map where keys are route names and values are functions returning the screen widgets.
Examples
This code moves the user to the screen named '/settings'.
Flutter
Navigator.pushNamed(context, '/settings');Defines two named routes: '/' for home and '/profile' for profile screen.
Flutter
MaterialApp( initialRoute: '/', routes: { '/': (context) => HomeScreen(), '/profile': (context) => ProfileScreen(), }, )
This code goes back to the previous screen in the navigation stack.
Flutter
Navigator.pop(context);
Sample App
This app starts at the Home screen. Pressing the button moves to the About screen using a named route. The About screen has a button to go back.
Flutter
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( initialRoute: '/', routes: { '/': (context) => HomeScreen(), '/about': (context) => AboutScreen(), }, ); } } class HomeScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Home')), body: Center( child: ElevatedButton( onPressed: () { Navigator.pushNamed(context, '/about'); }, child: Text('Go to About'), ), ), ); } } class AboutScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('About')), body: Center( child: ElevatedButton( onPressed: () { Navigator.pop(context); }, child: Text('Back to Home'), ), ), ); } }
OutputSuccess
Important Notes
Always use unique names for each route to avoid confusion.
You can pass data between screens using arguments with named routes.
Use Navigator.pop(context) to go back to the previous screen.
Summary
Named routes give each screen a simple name for easy navigation.
Define routes in MaterialApp with a map of names to screen widgets.
Use Navigator.pushNamed() to move to a screen and Navigator.pop() to go back.