You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter使用GetX实现侧边菜单状态切换不生效问题求助

问题成因
  • 没有使用GetX提供的响应式UI组件包裹需要监听状态变化的Widget,selectedIndex是Rx类型变量,但UI没有监听它的变化,值更新后不会触发重绘,所以视觉上没有变化。
  • 代码存在不规范写法:在_SideMenuState和DrawerListTile中两次调用Get.put(TileColorX()),虽然默认同类型无tag的控制器会复用实例,但特殊场景下可能出现状态不同步的问题。
修复方案
  1. 调整控制器获取逻辑:删除DrawerListTile中的Get.put语句,改用Get.find获取已经注册的TileColorX实例,避免重复注册。
  2. 增加响应式监听:使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 20:45:04