As your Flutter applications grow, you'll often need to pass data between screens. This is a common requirement for features like displaying user details, configuring settings, or selecting an item from a list. Flutter provides a robust and intuitive way to handle this data transfer during navigation, ensuring your app remains dynamic and responsive to user actions.
The primary mechanism for passing data during navigation is through arguments. When you navigate to a new route, you can include a set of arguments that the destination route can then access. These arguments can be of any Dart type, from simple strings and integers to complex custom objects.
Let's consider a scenario where we have a list of users and we want to tap on a user to see their profile. When we navigate from the user list screen to the user profile screen, we'll need to pass the ID or the entire user object of the selected user.
When navigating to a new route using Navigator.push, you can pass arguments as the second parameter. This argument can be a single value or a Map for passing multiple named arguments.
Navigator.push(context, MaterialPageRoute(builder: (context) => UserProfileScreen(userId: user.id)));On the destination screen (UserProfileScreen in this case), you'll need to declare a constructor that accepts these arguments. This allows the screen to receive and store the data passed from the previous screen.
class UserProfileScreen extends StatelessWidget {
final String userId;
const UserProfileScreen({Key? key, required this.userId}) : super(key: key);
@override
Widget build(BuildContext context) {
// Use userId to fetch and display user details
return Scaffold(
appBar: AppBar(title: Text('User Profile')),
body: Center(child: Text('Profile for user ID: $userId')),
);
}
}For more complex data or when you need to pass multiple pieces of information, using a Map as an argument is a flexible approach. This allows you to pass named arguments, making your code more readable and maintainable.