How to send parameters when navigating with Navigator.pushNamed

5,382

Solution 1

The first way is what I use in my app.

Navigator.pushNamed('/route/1');

Don't forget to use onGenerateRoute and pass the value. Example from my app:

routes: {
        '/': (BuildContext context) => AuthPage(),
        '/products': (BuildContext context) => ProductsPage(''),
        '/admin': (BuildContext context) =>
            ProductsAdminPage(_addProduct, _deleteProduct),
      },
      onGenerateRoute: (RouteSettings settings) {
        final List<String> pathElements = settings.name.split('/');
        if (pathElements[0] != '') {
          return null;
        }
        if (pathElements[1] == 'product') {
          return MaterialPageRoute<bool>(
            builder: (BuildContext context) => ProductPage(pathElements[2]),
          );
        }
        return null;
      },
      onUnknownRoute: (RouteSettings settings) {
        return MaterialPageRoute(
            builder: (BuildContext context) => ProductsPage('Error'));
      },

Solution 2

For the direct answer to your question, see this duplicate question: How do I pass non-string data to a named route in Flutter?

However, most of the times the best way to do this is to not pass parameters between routes, but use app-state-management. For example Redux or Bloc. Where you generally modify the state while in the first screen, then navigate to the second screen and read the state. This has the advantage of being able to persist the state and reopen your app in the same state where it was closed. For more information on state management see the official docs.

Share:
5,382
Joseph Arriaza
Author by

Joseph Arriaza

I am a full stack developer that have knowledge in a lot of technologies, like front end frameworks, like Angular, AngularJS, ReactJS, etc, also I have a knowledge using back end technologies, building APIs using Java, PHP &amp; C#. In my current work, we give services to companies in the US, so far, I have worked for Telecom Service Bureau building APIs and Front End interfaces, and also I work for Front Stream giving support to its system.

Updated on December 08, 2022

Comments

  • Joseph Arriaza
    Joseph Arriaza over 1 year

    I need to send some params to a named route. I would like to do something like:

    Navigator.pushNamed('/route/1');
    

    Or

    Navigator.pushNamed('/route?param1=1');
    

    I don't know if there is a way to do that, I am using MaterialApp with router.