Move Using Named Routes
Move Using Named Routes in Flutter
Named routes provide a clear and easy way to manage navigation between screens. Instead of navigating directly to a widget, you use a string identifier (the route’s name) to tell Flutter which screen to show.
Navigator.pushNamed(context, '/routeName')
Example 1: Move To Another Screen Using Named Routes
In this example below, there is HomeScreen and ProfileScreen. When you click a button on the home screen, it navigates to the profile screen. First, let’s create a MaterialApp with named routes.
Step 1: Define Named Routes
Define the named routes in the MaterialApp widget:
MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => HomeScreen(),
'/profile': (context) => ProfileScreen(),
},
);
Home Screen (HomeScreen)
This is the main screen of the application.
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Home Screen"),
),
body: Center(
child: ElevatedButton(
child: Text('Go to Profile Page'),
onPressed: () {
// Navigation Code Here
},
),
),
);
}
}
Profile Screen (ProfileScreen)
A page displaying profile information.
class ProfileScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Profile Page"),
),
body: Center(
child: Text("Welcome to the Profile Page!"),
),
);
}
}
Navigate To The New Screen
When the button is pressed, HomeScreen should navigate to ProfileScreen. Use the Navigator.pushNamed method to move to the new screen:
Navigator.pushNamed(context, '/profile');