Andy B.
Andy B.

Reputation: 164

Flutter: selected Icon on BottomNavigationBar doesn't change when tap

I work on flutter and I make an app with 5 tabs, using a BottomNavigationBar, who change the currently displayed content. When I tap on a tab, the content updates to the new content, but the tabs icon doesn't change. Home page screen Train page screen

I have tried to change the BottomNavigationBarType but that changes nothing...

here is base page widget:

class Home extends StatefulWidget {
  Home({Key key}) : super(key: key);

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

class _Home extends State<Home> {
  int _selectedIndex = 0;

  static List<Widget> _widgetOptions = <Widget>[
    HomePage(),
    CreateTrain(),
  ];

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }
  @override
  Widget build(BuildContext context) {
    print(_selectedIndex);
    return Scaffold(
      body: _widgetOptions.elementAt(_selectedIndex),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: 0, // this will be set when a new tab is tapped
        items: [
          BottomNavigationBarItem(
            icon: new Icon(Icons.home),
            title: new Text('Home'),
          ),
          BottomNavigationBarItem(
            icon: new Icon(Icons.assignment),
            title: new Text('Training'),
          ),
          BottomNavigationBarItem(
            icon: new Icon(Icons.play_arrow),
            title: new Text('start'),
          ),
          BottomNavigationBarItem(
            icon: new Icon(Icons.insert_chart),
            title: new Text('Stats'),
          ),
          BottomNavigationBarItem(
              icon: Icon(Icons.person), title: Text('Profile'))
        ],
        selectedFontSize: 12,
        unselectedFontSize: 12,
        selectedItemColor: Colors.amber[800],
        unselectedItemColor: Colors.grey[500],
        showUnselectedLabels: true,
        type: BottomNavigationBarType.fixed,
        onTap: _onItemTapped,
      ),
    );
  }
}

Here is HomePage widget:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: true,
        title: const Text(
          'Home',
          style: TextStyle(
            color: Colors.black,
            fontSize: 30,
          ),
        ),
        backgroundColor: _bgColor,
      ),
      body: Text('data'),
    );
  }
}

Thanks for your help.

Upvotes: 2

Views: 2497

Answers (1)

anmol.majhail
anmol.majhail

Reputation: 51206

In your code

  currentIndex: 0, // this will be set when a new tab is tapped

This should be

  currentIndex: _selectedIndex, // this will be set when a new tab is tapped

Upvotes: 3

Related Questions