flutterflutter-routes

Flutter AutoTabsRoute.pageview child not changes (auto_route)


I'm using the auto_route package for routing in my app. I want to use the AutoTabsRoute.pageview widget to create Scaffold with routing tabs.

I don't know why, but the builder should return a different child each time, but it produces the same child. For that reason, the selected tab changes, while the body does not.

enter image description here

Here is my code:

return AutoTabsRouter.pageView(
  routes: const [
    MainRoute(),
    MaintenanceRoute(),
    PaymentsRoute(),
  ],
  builder: (context, child, _) {
    return Scaffold(
      appBar: AppBar(
        title: Text(context.topRoute.name),
        leading: const AutoLeadingButton(),
      ),
      body: child,
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: currentIndex,
        onTap: (index) =>
            context.read<MenuCubit>().setTab(MenuTabs.values[index]),
        items: const [
          BottomNavigationBarItem(
            label: 'Main',
            icon: Icon(Icons.home),
          ),
          BottomNavigationBarItem(
            label: 'Maintenance',
            icon: Icon(Icons.work),
          ),
          BottomNavigationBarItem(
            label: 'Payment',
            icon: Icon(Icons.payment),
          ),
        ],
      ),
    );
  },
);

Why is that happening?


Solution

  • Issue solved!

    If you want the child parameter to change, you have to config:

    final tabsRouter = AutoTabsRouter.of(context);
    

    inside the builder, and update the index using it only:

    onTap: tabsRouter.setActiveIndex
    

    Full example:

    return AutoTabsRouter.pageView(
      routes: const [
        MainRoute(),
        MaintenanceRoute(),
        PaymentsRoute(),
      ],
      builder: (context, child, _) {
        final tabsRouter = AutoTabsRouter.of(context); // <--- configure the AutoTabsRouter parameter
    
        return Scaffold(
          appBar: AppBar(
            title: const Text('Home365'),
            actions: [
              IconButton(
                onPressed: () {},
                icon: const Icon(Icons.notifications_none),
              )
            ],
          ),
          body: child,
          bottomNavigationBar: BottomNavigationBar(
            currentIndex: tabsRouter.activeIndex, <--- use it here
            onTap: tabsRouter.setActiveIndex, <--- use it here
            items: const [
              BottomNavigationBarItem(
                label: 'Main',
                icon: Icon(Icons.home),
              ),
              BottomNavigationBarItem(
                label: 'Maintenance',
                icon: Icon(Icons.work),
              ),
              BottomNavigationBarItem(
                label: 'Payment',
                icon: Icon(Icons.payment),
              ),
            ],
          ),
        );
      },
    );