flutterflutter-bottomnavigation

flutter bottomNavigationBar not changing screens


I'm new to flutter, trying to implement BottomNavigationBar in a demo app. Bottom bar does show in app but can't change the current item on tapping, neither does the screen changes.

I've tried various methods to load screens but seems like the onTap function is not getting called.

Here is my code.

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {

    final Size screenSize = MediaQuery.of(context).size;

    int _currentTab = 0;

    Widget body() {
      switch (_currentTab) {
        case 0:
          return FeedScreen();
        case 1:
          return SearchScreen();
        case 2:
          return ProfileScreen();
        default:
          return FeedScreen();
      }
    }

    return Scaffold(
      bottomNavigationBar: BottomNavigationBar(
        onTap: (newValue) {
          setState(() {
            _currentTab = newValue;
          });
        },
        currentIndex: _currentTab,
        items: [
          BottomNavigationBarItem(
            icon: ImageIcon(
              AssetImage('images/home.png'),
            ),
            title: SizedBox.shrink(),
          ),
          BottomNavigationBarItem(
            icon: ImageIcon(
              AssetImage('images/search.png'),
            ),
            title: SizedBox.shrink(),
          ),
          BottomNavigationBarItem(
            icon: CircleAvatar(
              radius: 15,
              backgroundImage: AssetImage('images/avatar.png'),
            ),
            title: SizedBox.shrink(),
          )
        ],
      ),
      appBar: PreferredSize(
        preferredSize: Size(screenSize.width, 50.0),
        child: CustomAppBar(),
      ),
      body: body(),
    );
  }
}

Solution

  • your int _currentTab = 0; is inside build method. put it outside.

    everytime you trigger the setState, _currentTab will always be equal to 0 which is the FeedScreen because the variable is inside the build method