Flutter Navigation is an essential feature for creating a seamless user experience in your mobile apps. In this tutorial, we will cover how to use Named Routes to navigate between screens in your Flutter app.
Named Routes are pre-defined paths that map to specific screens in your Flutter app. With Named Routes, you can easily navigate to a new screen by calling the name of the route. This is a great way to manage navigation throughout your app and keep your code organized.
To use Named Routes in your Flutter app, you need to define the routes in your MaterialApp or CupertinoApp widget. Here is an example:
MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: '/',
routes: {
'/': (context) => HomePage(),
'/second': (context) => SecondScreen(),
'/third': (context) => ThirdScreen(),
},
);}
In the example above, we define three routes: '/' which is the home page, '/second', and '/third'. Each route maps to a specific screen that we define with a StatelessWidget or StatefulWidget. For example, if we want to navigate to the SecondScreen, we can simply call '/second' using the Navigator.pushNamed() method.
Navigator.pushNamed(context, '/second');}
This will take us to the SecondScreen in our app.
One advantage of Named Routes is that you can easily pass data between screens. Here is an example of how to pass data with Named Routes:
Navigator.pushNamed(
context,
'/second',
arguments: ScreenArguments(
'Screen Title',
'This is the message.',
),
);}
In the example above, we pass a ScreenArguments object that contains a title and a message to the SecondScreen. To access the arguments in the SecondScreen, we need to extract them from the ModalRoute. Here is how you can do it:
class SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final ScreenArguments args = ModalRoute.of(context).settings.arguments;
return Scaffold(
appBar: AppBar(
title: Text(args.title),
),
body: Center(
child: Text(args.message),
),
);
}
}
Named Routes are an essential feature in Flutter Navigation. With Named Routes, you can easily manage navigation throughout your app and keep your code organized. Additionally, passing data between screens is simple and intuitive.