Reputation: 5799
What will be equivalent of the below Flutter Navigator in terms of Go Router?
Navigator.pushNamed(
context,
Routes.CHANNEL_PAGE,
arguments:ChannelPageArgs(
channel:channel,
initialMessage:message,
),
);
Usually Go Router is based on parameters from the path. But the above example is based on a object instead of primitive parameters.
GoRoute(
path: '/profile/:id',
builder: (context, state) => ProfilePage(id: state.params['id']!),
),
Upvotes: 3
Views: 5259
Reputation: 24910
There are three ways params
,queryParams
,extra
params
path = '/routeName/:id1/:id2'
queryParams
path = '/routeName'
extra
object
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
.
GoRoute(
path: "/settings/:name",
builder: (context, state) => SettingsPage(
name: state.params["name"]!,
),
);
class SettingsPage extends StatelessWidget {
final String name;
const SettingsPage({super.key, required this.name});
@override
Widget build(BuildContext context) {
return Scaffold();
}
}
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.
child: ElevatedButton(
onPressed: () => context.goNamed("settings",
queryParams: {
"email": "[email protected]",
"age": "25",
"place": "India"
}),
child: const Text("Go to Settings page"),
),
GoRoute(
name: "settings",
path: "settings",
builder: (context, state) {
state.queryParams.forEach(
(key, value) {
print("$key:$value");
},
);
return SettingsPage();
},
)
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.
Upvotes: 5
Reputation: 1998
you can pass object as an extra
like this:
final args = ChannelPageArgs(
channel:channel,
initialMessage:message,
)
context.pushNamed('profile', extra: args)
in your goRouter:
GoRoute(
path: 'profile',
name: 'profile',
pageBuilder: (context, state) {
final args = state.extra as ChannelPageArgs;
return MaterialPage(
key: state.pageKey,
child: ProfilePage(
args: args,
),
Upvotes: 4