How should I change currentIndex property of BottomNavigationBar on Navigating to another screen?

121

Use the _selectedIndex with a PageView and set the onTap like this :

          currentIndex: _selectedIndex,
          selectedItemColor: Colors.grey[900],
          unselectedItemColor: Colors.grey[50],
          onTap: (int index) {
              setState(()=>_selectedIndex=index);
            }

Reading this article would be helpful

Edit: This is a full example

class MyHomePage extends StatefulWidget {
  MyHomePage({
    Key? key,
  }) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _selectedIndex = 0;
  late PageController _pageController;
  @override
  void initState() {
    super.initState();
    _pageController = PageController(
      initialPage: _selectedIndex,
    );
  }

  Widget build(BuildContext context) {
    return Scaffold(
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _selectedIndex,
          onTap: (index) {
            setState(() {
              _selectedIndex = index;
              _pageController.animateToPage(index,
                  duration: Duration(milliseconds: 500), curve: Curves.ease);
            });
          },
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: "Home",
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.search),
              label: "Search",
            ),
          ],
        ),
        appBar: AppBar(
          title: Text('Test App'),
        ),
        body: PageView(
          controller: _pageController,
          onPageChanged: (index) {
            setState(() {
              _selectedIndex = index;
            });
          },
          children: [
            Container(
              color: Colors.red,
              child: Center(
                child: Text("Home"),
              ),
            ),
            Container(
              color: Colors.green,
              child: Center(
                child: Text("Search"),
              ),
            ),
          ],
        ));
  }
}
Share:
121
enggPS
Author by

enggPS

Computer Engineering Student.

Updated on December 19, 2022

Comments

  • enggPS
    enggPS over 1 year

    I have a bottom navigation bar widget for my Flutter app. On tapping specific item it is navigating to another screen. However, I don't know how to update current index in this case so that selected tab gets highlighted. Here is my code:

            BottomNavigationBar(
              backgroundColor: const Color(0xffFF7B19),
              items: <BottomNavigationBarItem>[
                BottomNavigationBarItem(
                  icon: Icon(
                    Icons.calendar_today_rounded,
                    size: lh / 25,
                  ),
                  label: 'Events',
                ),
                BottomNavigationBarItem(
                  icon: Icon(
                    Icons.people_alt_outlined,
                    size: lh / 25,
                  ),
                  label: 'Councils',
                ),
              ],
              currentIndex: 0,
              selectedItemColor: Colors.grey[900],
              unselectedItemColor: Colors.grey[50],
              onTap: (int index) {
                if (index == 0) {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => AllEventsScreen()));
                } else {
                  Navigator.push(
                      context, MaterialPageRoute(builder: (context) => Councils()));
                }
              })
    

    Here is the output

    I have tried creating a variable _selectedIndex for this which I was updating inside the function I have provided for onTap as shown:

              currentIndex: _selectedIndex,
              selectedItemColor: Colors.grey[900],
              unselectedItemColor: Colors.grey[50],
              onTap: (int index) {
                if (index == 0) {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => AllEventsScreen()));
                  _selectedIndex = 0;
                } else {
                  Navigator.push(
                      context, MaterialPageRoute(builder: (context) => Councils()));
                  _selectedIndex = 1;
                }
    

    But this doesn't seems to work. I couldn't figure out how to do this.

  • enggPS
    enggPS about 2 years
    adding setState() method doesn't seems to work properly. It may be changing the current index but that becomes visible after navigating again to the original screen and not changing when it is clicked.
  • Youssef Elmoumen
    Youssef Elmoumen about 2 years
    If you want to save the state of the selected index use Provider or Bloc for state management