簡體   English   中英

帶有底部導航欄的 Flutter GetX 不更新小部件

[英]Flutter GetX with bottom navigation bar not update the widget

實際上,我已經解決了這個問題。 但這是奇怪的實現。 也許這種情況有更好的解決方案。

所以,我有基於底部導航索引顯示的屏幕列表

 List<Widget> screenList = [
    HomeScreen(),
    KategoriScreen(),
    PesananScreen(),
    AccountScreen()
  ];
 @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Obx(() {
        var user = Get.find<AccountController>().user.value; // <= weird Solution to trigger update
        return screenList.elementAt(_mIndex);
      }),
      bottomNavigationBar: _bottomNavWidget(),
    );
  }

其中一個 Screen 在小部件中有 Obx() 。 但是當數據發生變化時。 屏幕沒有更新。 我們需要更改屏幕索引,然后返回該屏幕以更新小部件。 所以,我目前的解決方案是在 Scaffold 中添加 Obx() 來處理帶有無用 var (var user) 的底部導航欄邏輯。 任何更好的解決方案?

更新

很抱歉對於這個誤會。 我的問題是帳戶控制器何時更新。 屏幕不更新。 需要更換其他屏幕並返回。 另一種解決方案是在父 Widget 中使用 Obx()。 但不使用用戶值

這就是狀態管理的原理。 您需要設置狀態或通知偵聽器以刷新 UI。

在這里,如果它不是您正在觀看的控制器,則僅使用 Obx 是不夠的。

我建議您從屏幕列表中創建一個類

class ScreenController extends GetxController{
   int _selectedIndex = 0.obs;
   List<Widget> _screenList = [
    HomeScreen(),
    KategoriScreen(),
    PesananScreen(),
    AccountScreen()
  ];

   selectIndex(int index) => selectedIndex = index;
   getScreen() => _screenList[_selectedIndex];
}

然后你可以簡單地將你的 _selectedIndex 封裝在你的 Obx 小部件中,當另一個按鈕使用 selectIndex 方法時,它將觸發刷新。

(你需要像往常一樣先put ScreenController)

class ScreenController extends GetxController {
  var tabIndex = 0;

  void changeTabIndex(int index) {
    tabIndex = index;
    update();
  }
}

這適用於您可以使用 indexstack 的小部件屏幕頁面

GetBuilder<DashboardController>(
      builder: (controller) {
        return Scaffold(
          body: SafeArea(
            child: IndexedStack(
              index: controller.tabIndex,
              children: [
                Home(),
                HotDeals(),
               ProfilePage(),

              ],
            ),
          ),
          bottomNavigationBar: BottomNavigationBar(
            unselectedItemColor: Colors.black,
            selectedItemColor: Colors.redAccent,
            onTap: controller.changeTabIndex,
            currentIndex: controller.tabIndex,
            showSelectedLabels: true,
            showUnselectedLabels: true,
            type: BottomNavigationBarType.fixed,
            backgroundColor: Colors.white,
            elevation: 0,
            items: [
              _bottomNavigationBarItem(
                icon: CupertinoIcons.home,
                label: 'Home',
              ),

              _bottomNavigationBarItem(
                icon: CupertinoIcons.photo,
                label: 'Hotdeals',
              ),
             
              _bottomNavigationBarItem(
                icon: CupertinoIcons.person,
                label: 'Profile',
              ),
            ],
          ),
        );
      },
    );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM