如何解决带有底部导航栏的 Flutter GetX 不更新小部件
实际上,我已经解决了这个问题。但这是奇怪的实现。对于这种情况,也许有更好的解决方案。
所以,我有根据底部导航索引显示的屏幕列表
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',);
},);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。