I want to create BottomNavigationBar with GetX state management. I keep my page index on my GetXController.
class PagerController extends GetxController {
RxInt pageIndex = 0.obs;
changePageTo(int index) {
pageIndex.value = index;
}
}
Here is my BottomNavigationBar widget. It is stateless.
BottomNavigationBar(
showSelectedLabels: false,
showUnselectedLabels: false,
selectedItemColor: Palette.kSelectedCategoryColor,
unselectedItemColor: Palette.kUnselectedCategoryTextColor,
elevation: 0,
enableFeedback: false,
currentIndex: controller.pageIndex.value,
items: items,
onTap: (index) => controller.changePageTo(index),
);
onTap my body is changing. But my bottom navigation bar's active icon color is not changing. In my opinion it causes for currentIndex property. I put controller.pageIndex.value
, but it is not listening value, it renders only one time. How to solve it?
CodePudding user response:
First of all, u should change pageIndex
's type from RxInt
to int
or just var
(adding .obs
is enough).
Second of all, in order for the BottomNavigationBar
to update, u need to wrap it in Obx()
, for example :
Obx(() => BottomNavigationBar(
showSelectedLabels: false,
showUnselectedLabels: false,
selectedItemColor: Palette.kSelectedCategoryColor,
unselectedItemColor: Palette.kUnselectedCategoryTextColor,
elevation: 0,
enableFeedback: false,
currentIndex: controller.pageIndex.value,
items: items,
onTap: (index) => controller.changePageTo(index),
)
)
CodePudding user response:
I think you could use GetBuilder. I past my DashBoard page code by replacing your navBar code with. In this case, don't event need to put obs(in controller) and Obx(in view).
Widget build(BuildContext context) {
return GetBuilder<DashBoardController>(builder: (controller) {
return Scaffold(
body: SafeArea(
child: IndexedStack(
index: controller.pageIndex,
children: [
HomeScreen(),
MeScreen(),
],
),
),
bottomNavigationBar: BottomNavigationBar(
showSelectedLabels: false,
showUnselectedLabels: false,
selectedItemColor: Palette.kSelectedCategoryColor,
unselectedItemColor: Palette.kUnselectedCategoryTextColor,
elevation: 0,
enableFeedback: false,
currentIndex: controller.pageIndex,
items: items,
onTap: controller.changePageTo,
),
);
});
}
In dash_board_controller.dart, we got changePageTo method in the controller. It executes a update which does the page refresh work.
class DashBoardController extends GetxController {
var tabIndex = 0;
var getToNamedList = [
Routes.HOME,
Routes.ME,
];
final List<BottomNavigationBarItem> navTabList = <BottomNavigationBarItem>[
BottomNavigationBarItem(
activeIcon: ImageIcon(
AssetImage('assets/***.png'),
size: 24,
),
icon: ImageIcon(
AssetImage('assets/***.png'),
size: 24,
),
label: "Home",
),
BottomNavigationBarItem(
activeIcon: ImageIcon(
AssetImage('assets/***.png'),
size: 24,
),
icon: ImageIcon(
AssetImage('assets/***.png'),
size: 24,
),
// icon: Icon(Icons.person),
label: "Me",
),
];
void changePageTo(int index) {
tabIndex = index;
update();
}
}