does anybody know why my Bottom navigation bar item isn't changing color when selected or deselected. It is Navigating to the correct screen, but the home item is always blue for some reason. Any help would be appreciated.
import 'package:flutter/material.dart';
import 'package:only_johns_lower_sdk/views/screens/nav_screens.dart/home_screen.dart';
import 'package:only_johns_lower_sdk/views/screens/nav_screens.dart/profile_screen.dart';
import 'package:only_johns_lower_sdk/views/screens/nav_screens.dart/users_screen.dart';
class MainPage extends StatefulWidget {
const MainPage({super.key});
@override
State<MainPage> createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
int _pageIndex = 0;
final List<Widget> _pages = [
const HomeScreen(),
const ProfileScreen(),
const UsersScreen()
];
void _onItemTapped(index) {
setState(() {
_pageIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: _pages[_pageIndex],
bottomNavigationBar: BottomNavigationBar(
selectedItemColor: Colors.blue,
unselectedItemColor: Colors.grey,
onTap: _onItemTapped,
items: const [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.person), label: 'Profile'),
BottomNavigationBarItem(icon: Icon(Icons.person_search), label: 'Johns'),
],),
);
}
}
The code you've provided sets up a bottom navigation bar with three items and changes the displayed page when an item is tapped. However, you're facing an issue where the color of the selected item does not change as expected. The issue might be related to not setting the
currentIndexproperty of theBottomNavigationBar. This property needs to be updated to tell theBottomNavigationBarwhich item is currently selected, so it can adjust the color accordingly.HEre is some code you can use, also some hints:
Make sure you set the
currentIndexproperty of yourBottomNavigationBarto the_pageIndexvariable. This links the navigation bar's state to your page controller.Ensure that the
selectedItemColorandunselectedItemColorare correctly set, which you've already done.Here is the corrected version of your
buildmethod:By adding the
currentIndex: _pageIndex,line, you're informing theBottomNavigationBarwhich item is currently selected based on the value of_pageIndex. This should resolve the issue with the color not changing when items are selected or deselected.Let me know if this worked for you.