Is there any way to insert a query parameters to a named route in flutter web?

Viewed 3588

I want to insert query parameters to a named route.

I have this code on my MaterialApp

Widget build(BuildContext context) {
    return MaterialApp(
    title: 'Web',
      theme: ThemeData(
        primarySwatch: Colors.amber,
      ),
      
        
    // Start the app with the "/" named route. In this case, the app starts
    // on the FirstScreen widget.
    initialRoute: '/login',
    routes: {
     
      '/login': (context) => LoginPage(),
      '/mainmenu': (context) => MainMenu(),
    
    },
    
  );
  }

Now I want to insert query parameters (for example id) to '/mainmenu' so when I want to navigate to the main menu page, the URL becomes for example: http://localhost:57430/#/mainmenu/?id=1234. Is there any way to do that? Thanks

3 Answers

You can pass Data through Navigator in Flutter by,

Navigator.pushReplacementNamed(context, '/home', arguments: {
        'id': 1234 
      });

In the above code you will be pass data as a map to the next screen using arguments.

You can decode the map by these steps:

  1. declaring a Map variable in the next screen

Map data = {}

  1. and decoding it by
data = ModalRoute.of(context).settings.arguments;
print(data);

Regards, Roshan

Flutter has a cookbook specially for this situation. Link here

It's recommended to create a class to specify the arguments that need to be passed to the route, for example:

class MainMenuArguments {
  final int id;
  MainMenuArguments(this.id);
}

That can be passed to a Navigator:

Navigator.pushNamed(context, MainMenuScreen.routeName, arguments: MainMenuArguments(1234)); // id = 1234

And can be then accessed from the MainMenu Widget:

class MainMenuScreen extends StatelessWidget {
  static const routeName = '/mainMenu';

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

    return Scaffold(
      body: Center(
        child: Text(args.id.toString()), // displays 1234
      ),
    );
  }
}

In order to do so, you'd need to register the route inside the MaterialApp constructor:

MaterialApp(
  routes: {
    MainMenuArgumentsScreen.routeName: (context) => MainMenuArgumentsScreen(),
  },
);
Related