'Change the bottom navigation screen and its index on button press

I am working on the bottom navigation bar feature. I have 4 screens associated with a bottom navigation bar.

  • Page1 Index0 (It has a button)
  • Page2 Index1
  • Page3 Index2
  • Page4 Index3

Each click on the bottom icon will change the index of a bottom navigation bar and triggers the specific screen to load.

Now I want to click on the button of screen 1 which is index 0 of a bottom navigation bar, this should make a call to load page2 as if I select the second icon of a bottom navigation bar.

I tried using the navigator.push(context,page()) which loaded the page however the bottom navigation bar was not visible. This is not the way, Is there any way to do it correctly?

Thanks



Solution 1:[1]

Use IndexedStack widget for this. Example is as follows:

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

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

class _HomeState extends State<Home> {
  int _currentIndex = 0; //Current selected index of the bottom navigation bar tab

  void changeTab(int index) {
    setState(() => _currentIndex = index);
  }

  @override
  Widget build(BuildContext context) {
    //List of Screens that you want to put
    final screens = [
      const Screen1(),
      const Screen2(),
      const Screen3(),
    ];

    return Scaffold(
      body: IndexedStack(
        index: _currentIndex,
        children: screens,
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (index) => changeTab(index),
        type: BottomNavigationBarType.fixed,
        unselectedItemColor: Colors.grey,
        selectedItemColor: Colors.red,
        showUnselectedLabels: false,
        showSelectedLabels: false,
        iconSize: 20,
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.foo),
            label: 'Screen1',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.bar),
            label: 'Screen2',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.baz),
            label: 'Screen3',
          ),
        ],
      ),
    );
  }
}

Solution 2:[2]

I fixed this issue using a Provider. The issue has been resolved now.

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 MD. Saffan Alvy
Solution 2 Kiran Rai Chamling