Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigator pass arguments with pushNamed

Tags:

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

like image 922
Syph Avatar asked Nov 14 '18 16:11

Syph


People also ask

How do you pass arguments in Navigator pushNamed?

Navigate to the widget Finally, navigate to the ExtractArgumentsScreen when a user taps a button using Navigator. pushNamed() . Provide the arguments to the route via the arguments property. The ExtractArgumentsScreen extracts the title and message from these arguments.

How do you pass parameters in pushNamed Flutter?

One can pass arguments to these routes using the arguments parameter of Navigator. pushNamed() method. Arguments can be extracted using the ModalRoute. of() method or using the onGenerateRoute() function.

What does Navigator pushNamed do?

With the widgets and routes in place, trigger navigation by using the Navigator. pushNamed() method. This tells Flutter to build the widget defined in the routes table and launch the screen.


1 Answers

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(...); } 
like image 102
badelectron77 Avatar answered Sep 24 '22 11:09

badelectron77