Navigating between different screens in a Flutter app is a crucial part of the development process. Flutter provides several widgets and approaches to achieve this, but perhaps the most commonly used one is the MaterialApp
widget.
The MaterialApp
widget is the root of a Flutter app and provides various features and configurations, including the ability to set up a navigation system easily. Using the MaterialApp
, you can define your app's routes and easily navigate between them.
Before you can navigate between screens, you must first define your app's routes. You can do this by providing a map of String
-WidgetBuilder
pairs to the routes
property of the MaterialApp
. The key is the route's name, and the value is a function that returns the widget to display when navigating to that route.
MaterialApp(
routes: {
'/': (context) => HomePage(),
'/settings': (context) => SettingsPage(),
'/profile': (context) => ProfilePage(),
},
);
In this example, we've defined three routes: '/'
for the homepage, '/settings'
for the settings page, and '/profile'
for the profile page. Note that the '/'
route specifies the HomePage
widget as its builder function.
Once you've defined your app's routes, you can use the Navigator
widget to navigate to them. The Navigator
widget maintains a stack of Route
objects, each representing a screen in your app. To push a new route onto the stack, use the Navigator.push()
method and specify the route's name:
Navigator.pushNamed(context, '/settings');
This code will push the SettingsPage
onto the stack and display it on the screen.
Often, you'll need to pass data between different screens in your app. You can do this by providing arguments to the Navigator.push()
method:
Navigator.pushNamed(context, '/profile', arguments: {
'name': 'John Doe',
'age': 25,
});
On the receiving end, you can access the passed arguments using the ModalRoute.of(context).settings.arguments
property:
class ProfilePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final args = ModalRoute.of(context).settings.arguments as Map<String, dynamic>;
final name = args['name'];
final age = args['age'];
return Scaffold(
appBar: AppBar(
title: Text('Profile'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Name: $name'),
Text('Age: $age'),
],
),
),
);
}
}
In this example, we've extracted the passed arguments to display them on the screen.
The MaterialApp
widget provides a straightforward way to set up navigation in a Flutter app. By defining routes and using the Navigator
widget, you can easily switch between different screens and pass data between them.