'How to use a dynamic index for bottom navigation bar in flutter

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!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source