2

I have built a bottom navigation bar in flutter using the following method:

Scaffold(
  appBar: AppBar(
    title: const Text('BottomNavigationBar Demo'),
  ),
  bottomNavigationBar: BottomNavigationBar(
    items: const <BottomNavigationBarItem>[
      BottomNavigationBarItem(
        icon: Icon(Icons.call),
        label: 'Calls',
      ),
      BottomNavigationBarItem(
        icon: Icon(Icons.camera),
        label: 'Camera',
      ),
      BottomNavigationBarItem(
        icon: Icon(Icons.chat),
        label: 'Chats',
      ),
    ],
  ),
);

int _selectedIndex = 0; //New
BottomNavigationBar(
  items: const <BottomNavigationBarItem>[
    ...
  currentIndex: _selectedIndex, //New
  onTap: _onItemTapped,         //New
)
//New
void _onItemTapped(int index) {
  setState(() {
    _selectedIndex = index;
  });
}

But, my requirement is to have the _selectedIndex as a dynamic value which should be set to the value that I give dynamically in the code. The actually reason why I am trying this is to navigate back to a specific page in the bottom navigation bar. Like, for example, I am in some other page without navigation bar and from there I use this piece of code to navigate to a specific page of navigation bar by passing the index:

Navigator.push(

        context,

        MaterialPageRoute(

          builder: (context) => CameraScreen(

            index : _selectedIndex,

          ),

        ));

This doesn't work, as it only moves to the page whose index I mentioned and all other onTap changes of index doesn't happen. Please help me fix this problem and the part I'm missing to understand. Thanks in advance!

yamini r
  • 153
  • 1
  • 15
  • Does this solve your issue? https://stackoverflow.com/a/50962613/3825725 – Vandad Nahavandipoor Feb 21 '22 at 08:18
  • No, this doesn't work for me. This is the same as I tried. I am unable to pass the desired index value from other page. If I pass so, it only accepts that index value and the further onTap() changes that has to happen when we click the icons in navigation bar is not happening. – yamini r Feb 21 '22 at 14:42

0 Answers0