Flutter – Navigator pass arguments with pushNamed

flutter

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)?

Best Answer

No need for onGenerateRoute. Simply use

var exampleArgument = 'example string';

Navigator.pushNamed(
    context,
    ImagesScreen.routeName,
    arguments: {'exampleArgument': exampleArgument},
);

and extract the arguments as follows:

@override
Widget build(BuildContext context) {
    final arguments = ModalRoute.of(context).settings.arguments as Map;

    if (arguments != null) print(arguments['exampleArgument']);

    return Scaffold(...);
}
Related Topic