Home > Mobile >  Flutter Bottom Navigation Bar not switching screens
Flutter Bottom Navigation Bar not switching screens

Time:08-10

I am new to flutter and this is my first time implementing bottom navigation bar in one of my projects but I'm so confused why it doesn't let me switch screens. Somehow I can tap the icon but it doesn't switch the page while tapping.

I got this code in one of the tutorials from Youtube and it seems like its working fine from the video.

class NavBar extends StatefulWidget {
  static const String route = 'navbar';
  const NavBar({Key? key}) : super(key: key);

  @override
  State<NavBar> createState() => _NavBarState();
}

class _NavBarState extends State<NavBar> {
  @override
  Widget build(BuildContext context) {
    int pageIndex = 0;
    final AuthController auth = locator<AuthController>();

    final List<Widget> pages = [
      const HomeScreen(),
      const ArtistsScreen(),
      const ChatHomeScreen(),
      const ProfileScreen(),
    ];

    return Scaffold(
      body: pages[pageIndex],
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        backgroundColor: const Color(0xffE28D00),
        selectedItemColor: Colors.white,
        unselectedItemColor: Colors.white70,
        currentIndex: pageIndex,
        elevation: 3,
        showUnselectedLabels: false,
        onTap: (int index) {
          setState(() {
            pageIndex = index;
          });
        },
        items: const [
          BottomNavigationBarItem(
            icon: FaIcon(FontAwesomeIcons.house),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: FaIcon(FontAwesomeIcons.music),
            label: 'Artists Hub',
          ),
          BottomNavigationBarItem(
            icon: FaIcon(FontAwesomeIcons.comment),
            label: 'Chat',
          ),
          BottomNavigationBarItem(
            icon: FaIcon(FontAwesomeIcons.user),
            label: 'Profile',
          ),
        ],
      ),
    );
  }
}

CodePudding user response:

Put pageIndex before build method. Else, when the state changes, build method calls and set pageIndex =0

  int pageIndex = 0;
  final List<Widget> pages = [
    const Text("A"),
    const Text("Ab"),
    const Text("As"),
    const Text("Ac"),
  ];

  @override
  Widget build(BuildContext context) {
  • Related