I want to insert query parameters to a named route.
I have this code on my MaterialApp
Widget build(BuildContext context) {
return MaterialApp(
title: 'Web',
theme: ThemeData(
primarySwatch: Colors.amber,
),
// Start the app with the "/" named route. In this case, the app starts
// on the FirstScreen widget.
initialRoute: '/login',
routes: {
'/login': (context) => LoginPage(),
'/mainmenu': (context) => MainMenu(),
},
);
}
Now I want to insert query parameters (for example id) to '/mainmenu' so when I want to navigate to the main menu page, the URL becomes for example: http://localhost:57430/#/mainmenu/?id=1234
. Is there any way to do that? Thanks
It's recommended to create a class to specify the arguments that need to be passed to the route, for example:
class MainMenuArguments {
final int id;
MainMenuArguments(this.id);
}
That can be passed to a Navigator
:
Navigator.pushNamed(context, MainMenuScreen.routeName, arguments: MainMenuArguments(1234)); // id = 1234
And can be then accessed from the MainMenu
Widget
:
class MainMenuScreen extends StatelessWidget {
static const routeName = '/mainMenu';
@override
Widget build(BuildContext context) {
final MainMenuArguments args = ModalRoute.of(context).settings.arguments;
return Scaffold(
body: Center(
child: Text(args.id.toString()), // displays 1234
),
);
}
}
In order to do so, you'd need to register the route inside the MaterialApp
constructor:
MaterialApp(
routes: {
MainMenuArgumentsScreen.routeName: (context) => MainMenuArgumentsScreen(),
},
);