skip to Main Content

Here is my code. It is successfully changing screens but the active tab is not changing. Any help? I would like that if the for example it click on profile it will automatically show that the profile tab is active.

class BottomNavBar extends StatefulWidget {
const BottomNavBar({super.key});

@override
_BottomNavBarState createState() => _BottomNavBarState();
}

class _BottomNavBarState extends State<BottomNavBar> {
int _selectedIndex = 0;

static final List<String> _routeNames = [
   '/home',
   '/booking',
   '/settings',
  '/profile'
];

... designs in omy code and Gnav Widget

Gnav(tabs: const [
            GButton(
              icon: LineIcons.home,
              text: 'Home',
            ),
            GButton(
              icon: LineIcons.bookOpen,
              text: 'Bookings',
            ),
            GButton(
              icon: LineIcons.cog,
              text: 'Settings',
            ),
            GButton(
              icon: LineIcons.user,
              text: 'Profile',
            ),
          ],)

selectedIndex: _selectedIndex,
   onTabChange: (index) {
      setState(() {
          selectedIndex = index;
          final goRouter = GoRouter.of(context);
          goRouter.push(_routeNames[index]);
      });
   },

2

Answers


  1. On setState, you are navigating to a new page. I think this is causing the problem.

    Instead of Navigating to a new page, you could just display the page of the selected index as the child in the same scaffold.

    You could do something like

    static final List<Widget> _pages = [
       Home(), Booking(), Setting(), Profile(),
    ];
    
    int _selectedIndex = 0;
    
    @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: ... ,
          body: _pages[_selectedIndex],
          bottomNavigationBar: GNav( ... ),
        );
      }
    Login or Signup to reply.
  2. check example provided within the package:
    https://pub.dev/packages/google_nav_bar/example

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search