skip to Main Content

I have demo code for bottom bar below but when I tap on second tab, related screen is not changing.
It is very basic example and should change tabs, may be it is silly mistake as I am just beginner in flutter.

I am using GetX for routing via GetMatrialApp.

so IntiialRoute is tab screen.

class TabScreen extends StatefulWidget {
  const TabScreen({super.key});

  @override
  State<TabScreen> createState() => _TabScreenState();
}

class _TabScreenState extends State<TabScreen> {
  @override
  Widget build(BuildContext context) {
    int currentIndex = 0;
    final List<Widget> screens = [const Text('A'), const Text('B')];

    return Scaffold(
      body: screens[currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: currentIndex,
        onTap: (index) {
          setState(() {
            currentIndex = index;
          });
        },
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: 'Profile',
          ),
        ],
      ),
    );
  }
}

It should show second tab screen.

2

Answers


  1. int currentIndex = 0; should defined in _TabScreenState instead of build method.

    class _TabScreenState extends State<TabScreen> {
      int currentIndex = 0;
    
      @override
      Widget build(BuildContext context) {
        final List<Widget> screens = [const Text('A'), const Text('B')];
    
        return Scaffold(
          body: screens[currentIndex],
          bottomNavigationBar: BottomNavigationBar(
            currentIndex: currentIndex,
            onTap: (index) {
              setState(() {
                currentIndex = index;
              });
            },
            items: const [
              BottomNavigationBarItem(
                icon: Icon(Icons.home),
                label: 'Home',
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.person),
                label: 'Profile',
              ),
            ],
          ),
        );
      }
    }
    
    Login or Signup to reply.
  2. The problem you are facing is because your variable

    int currentIndex = 0;
    

    is inside build methode. When you click on 2nd button while currentIndex is inside of build methode it will not change state.
    And if currentIndex is out side of build methode and you click on 2nd button it change from outside of build methode and then it change to second screen.
    So keep variables out side of build methode. Only place those variables inside build methode which need to initialz at once.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search