In Flutter, to pass non-string data to named routes, we typically use the arguments parameter within RouteSettings. Here, I'll demonstrate this with a concrete example.
First, let's assume we have a User object that we need to pass between different pages.
dartclass User { final String name; final int age; User(this.name, this.age); }
Next, when defining named routes, we set up parameter passing for the target page.
dart// Define routes MaterialApp( routes: { '/': (context) => HomePage(), '/user': (context) => UserPage(), }, onGenerateRoute: (settings) { if (settings.name == '/user') { final User user = settings.arguments as User; return MaterialPageRoute( builder: (context) { return UserPage(user: user); }, ); } // Other route handling return null; }, );
In the above code, we handle the specific route '/user' within the onGenerateRoute method. We receive the passed User object via the arguments property of the route settings.
Then, we can receive this User object in the constructor of the UserPage widget:
dartclass UserPage extends StatelessWidget { final User user; UserPage({required this.user}); Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('User Profile'), ), body: Center( child: Text('Name: ${user.name}, Age: ${user.age}'), ), ); } }
Finally, when navigating to the UserPage and passing user data, we do the following:
dartNavigator.pushNamed( context, '/user', arguments: User('John Doe', 30), );
This allows us to pass a User object from one page to another via named routes and use its data in the target page.
In summary, by using the arguments parameter within route settings, we can conveniently pass complex data objects between different pages in a Flutter application.