Flutter 使用Getx 構建底部導航bottomNavigationBar

第一步:配置文件引入getx

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  get: ^4.1.4

第二步:修改main()方法,並設置根節點組件

void main() {
  runApp(GetMaterialApp(home: MyApp()));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BootomNvPage();//底部導航組件
  }
}

第三步:全局狀態變量代碼

class MainState {
  //底部導航欄索引
  RxInt bottombar_index = 0.obs;
}

第四步:全局狀態控制器代碼

//全局狀態控制器
class GlobalStateController extends GetxController {
  MainState state = MainState();
  //改變底部導航欄索引
  changeBottomBarIndex(int index) {
    state.bottombar_index.value = index;
    print(state.bottombar_index.value);
  }
}

第五步:底部導航組件頁面完整代碼

class BootomNvPage extends StatelessWidget {
  //全局狀態控制器
  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]),
        //底部導航條
        bottomNavigationBar: Obx(() => BottomNavigationBar(
              // 當前菜單下標
              currentIndex: mainState.bottombar_index.value,
              // 點擊事件,獲取當前點擊的標籤下標
              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: "設置")
              ],
            )));
  }
}

運行結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章