第一步:配置文件引入getx
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
get: ^4.1.4
第二步:修改main()方法蚕礼,并設(shè)置根節(jié)點組件
void main() {
runApp(GetMaterialApp(home: MyApp()));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BootomNvPage();//底部導(dǎo)航組件
}
}
第三步:全局狀態(tài)變量代碼
class MainState {
//底部導(dǎo)航欄索引
RxInt bottombar_index = 0.obs;
}
第四步:全局狀態(tài)控制器代碼
//全局狀態(tài)控制器
class GlobalStateController extends GetxController {
MainState state = MainState();
//改變底部導(dǎo)航欄索引
changeBottomBarIndex(int index) {
state.bottombar_index.value = index;
print(state.bottombar_index.value);
}
}
第五步:底部導(dǎo)航組件頁面完整代碼
class BootomNvPage extends StatelessWidget {
//全局狀態(tài)控制器
final globalStateController = Get.put(GlobalStateController());
var mainState = Get.find<GlobalStateController>().state;
List bodyPageList = [
HomePage(),
InfoPage(),
MyPage(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
//主題
body: Obx(() =>bodyPageList[mainState.bottombar_index.value]),
//底部導(dǎo)航條
bottomNavigationBar: Obx(() => BottomNavigationBar(
// 當(dāng)前菜單下標
currentIndex: mainState.bottombar_index.value,
// 點擊事件,獲取當(dāng)前點擊的標簽下標
onTap: (int index) {
globalStateController.changeBottomBarIndex(index);
},
iconSize: 30.0,
fixedColor: Colors.red,
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), label: "首頁"),
BottomNavigationBarItem(icon: Icon(Icons.category), label: "分類"),
BottomNavigationBarItem(icon: Icon(Icons.settings), label: "設(shè)置")
],
)));
}
}