How to create named routes and use them for redirecting to another page in flutter?
First we have to initialize routes. Let’s check the code :
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
initialRoute: '/',
routes: {
'/' : (context) => StartPage(),
'/destinationRoute' : (context) => DestinationPage(),
},
);
}
}
routes: {
'/' : (context) => StartPage(),
'/destinationRoute' : (context) => DestinationPage(),
},
This is the main code to declare named routes.
Now let’s see how to use the named routes to navigate pages. We need to use Navigator.pushNamed()
for this.
Navigator.pushNamed(context, '/DestinationPage');