Summary:
There are three ways params
,queryParams
,extra
- Using
params
- When you know the number of parameters beforehand
- Usage :
path = '/routeName/:id1/:id2'
- Using
queryParams
- When you are not sure about the number of parameters
- Usage :
path = '/routeName'
- Using
extra
- When you want to pass
object
Explanation:
1. Using Params
If you want to add a name
parameter in the settings
route, the path argument should be /settings:name
. You can access the route parameter with the state.params["name"] variable
.
Define it as:
GoRoute(
path: "/settings/:name",
builder: (context, state) => SettingsPage(
name: state.params["name"]!,
),
);
Receive it as:
class SettingsPage extends StatelessWidget {
final String name;
const SettingsPage({super.key, required this.name});
@override
Widget build(BuildContext context) {
return Scaffold();
}
}
2. Using queryParams
You have access to queryParams
in the context.goNamed()
function. The best thing about queryParams
is that you don't have to explicitly define them in your route path and can easily access them using the state.queryParams
method. You can add miscellaneous user-related data as a query parameter.
Add Parameters like so
child: ElevatedButton(
onPressed: () => context.goNamed("settings",
queryParams: {
"email": "example@gmail.com",
"age": "25",
"place": "India"
}),
child: const Text("Go to Settings page"),
),
Receive it as :
GoRoute(
name: "settings",
path: "settings",
builder: (context, state) {
state.queryParams.forEach(
(key, value) {
print("$key:$value");
},
);
return SettingsPage();
},
)
3. Using extra
GoRoute(
path: '/sample',
builder: (context, state) {
Sample sample = state.extra as Sample; // -> casting is important
return GoToScreen(object: sample);
},
),
Refer https://stackoverflow.com/a/74813017/13431819 for passing object
between routes.