flutterauto-route

how to pass argument to nested route in auto_route?


I am using auto route and trying to implement persistent navigation bar with Nested Route.

my Routes:

List<AutoRoute> get routes => [
    AutoRoute(
      path: "/",
      initial: true,
      page: BaseRoute.page,
      children: [
        AutoRoute(
          path: "home_tab",
          page: HomeTabRoute.page,
          initial: true,
          children: [
            AutoRoute(path: "home_page", page: HomeRoute.page, initial: true),
          ],
        ),
        AutoRoute(
          path: "setting_tab",
          page: SettingTabRoute.page,
          children: [
            AutoRoute(
              path: "base_setting",
              page: SettingRoute.page,
              initial: true,
            ),
          ],
        )
      ],
    ),
  ];

I render them in my tab page

setting_tab_page:

@RoutePage()
class SettingTabPage extends StatelessWidget {
  const SettingTabPage({super.key});

  @override
  Widget build(BuildContext context) {
    return const AutoRouter();
  }
}

The problem I'm facing is, say that the initial screen have an argument or a required parameter like this

setting_page

class SettingPage extends StatelessWidget {
  final BuildContext context;
  const SettingPage({super.key, required this.context});
  

  @override
  Widget build(BuildContext context) {
    return Scaffold();
  }
}

How would I pass an argument/parameter to that first screen?


Solution

  • From the documentation you could notice that:

    AutoRoute automatically detects and handles your page arguments for you, the generated route object will deliver all the arguments your page needs including path/query params.

    But passing context is bad idea. may be you should pass params that you intent to retrieve from context.

    More info passing-arguments

    If your page is nested, nothing is changed. AutoRoute still automatically detects and handles your page arguments for you.

    AutoRouter.of(context).replace(
      const SettingRoute(..put your arguments),
    );
    

    as SettingRoute is initial in nested navigation you should replace/push/etc to the SettingRoute and not SettingTabPageRoute. and again - pass provider and not context then.