1、创建全局状态管理类
class MainState{
RxInt bottomBarIndex = 0.obs;
}
2、创建全局状态控制器
class GlobalStateController extends GetxController {
final MainState mainState = MainState();
changeBottomBarIndex(int index) {
mainState.bottomBarIndex.value = index;
}
}
3、实现底部BottomNavigationBar
class BottomNavBar extends StatelessWidget {
final GlobalStateController globalStateController =
Get.put(GlobalStateController());
var mainState = Get.find<GlobalStateController>().mainState;
List pages = [HomeView(), MyView()];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Obx(() => pages[mainState.bottomBarIndex.value]),
bottomNavigationBar: Obx(
() => BottomNavigationBar(
currentIndex: mainState.bottomBarIndex.value,
onTap: (index) {
globalStateController.changeBottomBarIndex(index);
},
type: BottomNavigationBarType.fixed,
iconSize: 30,
fixedColor: Colors.blue,
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: "首页"),
BottomNavigationBarItem(icon: Icon(Icons.settings), label: "我的"),
],
),
),
);
}
}
6、调用 navigationBar
@override
Widget build(BuildContext context) {
return BottomNavBar();
}
|