How to Pass Data to Named Routes in Flutter
Passing data to named routes in flutter involves three main steps:
1.Define the Named Route
2.Pass Data When Navigating
3. Retrieve Data in the Destination Route
1.Define the Named Route: First, you need to define the named routes in your MaterialApp
or CupertinoApp
widget. This is typically done in the routes
property.
MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => HomeScreen(),
'/details': (context) => DetailsScreen(),
}
);
Here, we’ve defined two routes: the home route (/
) and a details route (/details
).
2.Pass Data When Navigating: To pass data to a named route, use the arguments
parameter of the Navigator.pushNamed
method. This parameter can accept any type of data, such as a String
, Map
, or even a custom object.
Navigator.pushNamed(
'context',
'/details',
arguments: {
'title': 'Flutter Demo',
'message: 'Hello from the Home Screen',
},
);
In this example, we’re passing a Map
containing a title
and a message
to the DetailsScreen
.
3. Retrieve Data in the Destination Route: In the destination route, you can retrieve the data using ModalRoute.of(context)!settings.arguments
.
class DetailsScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
//Retrieve the arguments
final Map<String, String> args = ModalRoute.of(context)!.settings.arguments as Map<String, String>;
return Scaffold(
appBar: AppBar(
title: Text(args['title']!),
),
body: Center(
child: Text(args['message']!),
),
);
}
}
Here we’re casting the arguments
to Map<String, String>
and using the data to populate the AppBar
title and the body text.
If you’re working on a large app with complex navigation, consider using a state management solution like Provider
or Riverpod
to manage data flow between screens more effectively.