Flutter使用GetX实现侧边菜单状态切换不生效问题求助
问题成因
- 没有使用GetX提供的响应式UI组件包裹需要监听状态变化的Widget,
selectedIndex是Rx类型变量,但UI没有监听它的变化,值更新后不会触发重绘,所以视觉上没有变化。 - 代码存在不规范写法:在
_SideMenuState和DrawerListTile中两次调用Get.put(TileColorX()),虽然默认同类型无tag的控制器会复用实例,但特殊场景下可能出现状态不同步的问题。
修复方案
- 调整控制器获取逻辑:删除
DrawerListTile中的Get.put语句,改用Get.find获取已经注册的TileColorX实例,避免重复注册。 - 增加响应式监听:使用
Obx组件包裹DrawerListTile中返回的ListTile组件,当监听的selectedIndex值变化时,会自动触发这部分UI重绘。
修改后的核心代码
DrawerListTile组件
class DrawerListTile extends StatelessWidget { DrawerListTile({ Key? key, required this.title, required this.svgSrc, required this.press, required this.control, }) : super(key: key); final String title, svgSrc; final VoidCallback press; final int control; // 查找已注册的控制器,不要重复put final TileColorX tcx = Get.find<TileColorX>(); @override Widget build(BuildContext context) { // 用Obx包裹需要响应状态变化的组件 return Obx(() => ListTile( onTap: press, horizontalTitleGap: 0.0, leading: SvgPicture.asset( svgSrc, color: control == tcx.selectedIndex.value ? Colors.white : Colors.white54, height: 16, ), title: Text( title, style: TextStyle( color: control == tcx.selectedIndex.value ? Colors.white : Colors.white54), ), )); } }
可选优化
如果你的侧边菜单会在多个路由中复用,可以在SideMenu注册控制器时添加permanent: true参数,避免控制器被GetX自动回收:
TileColorX tcx = Get.put(TileColorX(), permanent: true);
内容的提问来源于stack exchange,提问作者rameez khan
相关产品推荐
相关产品推荐

