Flutter: value of currentIndex property in BottomNavigationBar doesn't update when the state updates

2,267

I would advise you to create a widget that will contain the BottomNavigationBar and also PageView that would allow you to switch pages with PageController. For example:

class _MainScreenState extends State<MainScreen> {
  PageController _pageController;
  int _page = 1;
  Duration pageChanging = Duration(milliseconds: 300);//this is for page animation-not necessary
  Curve animationCurve = Curves.linear;//this is for page animation-not necessary
  _MainScreenState();


@override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: 1);
  }


Widget build(BuildContext context) {
    return Scaffold(
      body: PageView(
        physics: BouncingScrollPhysics(),
        scrollDirection: Axis.horizontal,
        controller: _pageController,
        onPageChanged: onPageChanged,
        children: <Widget>[
          //here are all the pages you need:
          //CookRecipe(),
        ],
      ),
bottomNavigationBar: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          items: <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(
                Icons.message,
              ),
              title: Container(height: 0.0),
            ),
            BottomNavigationBarItem(
              icon: Icon(
                Icons.home,
              ),
              title: Container(height: 0.0),
            ),
            BottomNavigationBarItem(
              icon: Icon(
                Icons.person,
              ),
              title: Container(height: 0.0),
            ),
          ],
          onTap: navigationTapped,
          selectedItemColor: Theme.of(context).backgroundColor,
          currentIndex: _page,
        ),
      ),
    );
  }

void navigationTapped(int page) {
    _pageController.animateToPage(page,duration: pageChanging,
      curve: animationCurve,);
  }



  @override
  void dispose() {
    super.dispose();
    _pageController.dispose();
  }

  void onPageChanged(int page) {
    if (this.mounted){
    setState(() {
      this._page = page;
    });
  }}


You can also do this without the PageView,and use only the controller to switch pages.

BTW-you create new instance of the navigation bar when you load a page which is bad practice

Share:
2,267
Lisa
Author by

Lisa

Updated on December 19, 2022

Comments

  • Lisa
    Lisa over 1 year

    I have a BottomNavigationBar that navigates to other pages when pressing an icon. This works fine, except the value of the currentIndex property in BottomNavigationBar doesn't update when the state updates, which means there is no change on the acual BottomNavigationBar. enter image description here

    I'm using a vaiable (_selectedPage) to keep track of the selected index in the BottomNavigationBar, and the value changes when tapping an item, but it's not updating the currentIndex property when the state updates.. why is that?

    import 'package:flutter/material.dart';
    import 'package:independentproject/pages/home_page.dart';
    import 'package:independentproject/pages/cook_recipe.dart';
    
    class PageNavigationBar extends StatefulWidget {
      @override
      _PageNavigationBarState createState() => _PageNavigationBarState();
    }
    
    class _PageNavigationBarState extends State<PageNavigationBar> {
      //default page showing in bottom navigation bar will be CookRecipe()
      int _selectedPage = 1;
    
    //all pages optional in bottom navigation bar
      final List<Widget> _pageOptions = [
        HomePage(),
        CookRecipe(),
      ];
    
      void onTapped(int pageTapped) {
        setState(() {
          //print(pageTapped);
          _selectedPage = pageTapped;
          Navigator.push(context, MaterialPageRoute(builder: (context) => _pageOptions[pageTapped]));
          //print(_selectedPage);
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return BottomNavigationBar(
          //TODO: currentIndex: doesn't update when the state updates, why?
          currentIndex: _selectedPage,
            //items showing in bottom navigation bar
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text('Homepage'),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.search),
              title: Text('Search recipe'),
            ),
          ],
          onTap: (int pageTapped) {
            onTapped(pageTapped);
          },
        );
      }
    }
    
    
    import 'package:flutter/material.dart';
    import 'package:independentproject/page_navigation_bar.dart';
    
    class HomePage extends StatefulWidget {
      @override
      _HomePageState createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('Home page'),
            ),
            body: Center(
              child: Text('Home page'),
            ),
            bottomNavigationBar: PageNavigationBar(),
          ),
        );
      }
    }
    
    
    import 'package:flutter/material.dart';
    import 'package:independentproject/page_navigation_bar.dart';
    
    class CookRecipe extends StatefulWidget {
      @override
      _CookRecipeState createState() => _CookRecipeState();
    }
    
    class _CookRecipeState extends State<CookRecipe> {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('Search recipe'),
            ),
            body: Center(
              child: Text('Search recipes'),
            ),
            bottomNavigationBar: PageNavigationBar(),
          ),
        );
      }
    }