Navigator pass arguments with pushNamed
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(...);
}
It took me a while to notice this, as I'm a newbie to Flutter. But the arguments you add using Navigator.pushNamed
get sent directly to the widget you pushed NOT the MaterialApp for routing.
So in widget you push a new screen from you'll have:
Navigator.pushNamed(
context,
SomePage.routeName,
arguments: {
'v1': 'data1',
'v2': 'data2',
'v3': 'data3',
},
)
You won't need those arguments in your constructor at all. Instead your pull them out in the SomePage widget like the others are saying; namely via:
final arg = ModalRoute.of(context)!.settings.arguments as Map;
and can assign them within SomePage build like:
randomVar1 = arg['v1'];
randomVar2 = arg['v2'];
randomVar3 = arg['v3'];
using whatever keys you put in.
if you want MaterialApp to handle it then you use the onGenerateRoute method. This took me forever to notice that the arguments go directly to the widget pushed. For me it was counter-intuitive.
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.
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.