Navigator pass arguments with pushNamed
Might have been asked before but I can't find it but how do you pass a arguments to a named route?
This is how I build my routes
Widget build(BuildContext context) {
return new Navigator(
initialRoute: 'home/chooseroom',
onGenerateRoute: (RouteSettings settings) {
WidgetBuilder builder;
switch (settings.name) {
case 'home/chooseroom':
// navigates to 'signup/choose_credentials'.
builder = (BuildContext _) => new ChoosePage();
break;
case 'home/createpage':
builder = (BuildContext _) => new CreateRoomPage();
break;
case 'home/presentation':
builder = (BuildContext _) => new Presentation();
break;
default:
throw new Exception('Invalid route: ${settings.name}');
}
return new MaterialPageRoute(builder: builder, settings: settings);
},
);
This is how you call it
Navigator.of(context).pushNamed('home/presentation')
But what if my widget is new Presentation(arg1, arg2, arg3)
?
No need for onGenerateRoute
. Simply use
var exampleArgument = 'example string';
Navigator.pushNamed(
context,
'/otherscreen',
arguments: {'exampleArgument': exampleArgument},
);
and extract the arguments as follows:
@override
Widget build(BuildContext context) {
final arguments = (ModalRoute.of(context)?.settings.arguments ?? <String, dynamic>{}) as Map;
print(arguments['exampleArgument']);
return Scaffold(...);
}
pushNamed()
now supports arguments as of this merged pull request. If you can't wait, switch to channel master
(flutter channel master
and probably followed by flutter upgrade
).
How to send:
Navigator.pushNamed(ctx, '/foo', arguments: someObject);
How to receive:
...
return MaterialApp(
...
onGenerateRoute: _getRoute,
...
);
...
Route<dynamic> _getRoute(RouteSettings settings) {
if (settings.name == '/foo') {
// FooRoute constructor expects SomeObject
return _buildRoute(settings, new FooRoute(settings.arguments));
}
return null;
}
MaterialPageRoute _buildRoute(RouteSettings settings, Widget builder) {
return new MaterialPageRoute(
settings: settings,
builder: (ctx) => builder,
);
}
The "arguments" can be any object, e.g. a map.
Arguments can be any object, you can make an array as you can see:
Navigator.of(context).pushNamed('/upload', arguments: {'_imagePath':_imagePath,
'num_docfiscal':num_docfiscal,'dta_docfiscal':dta_docfiscal});
and access to the router class.