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

Flutter中NavigationRail结合GetX Obx无法实时更新数值问题

问题原因

你遇到的实时更新失效问题,核心原因是操作obs列表的方式错误,以及GetX响应式API混用:

  1. 直接调用filterCountry.value.add/remove属于原地修改列表内部元素,obs监听的是列表引用的变化,这种操作不会触发响应式更新。
  2. 你在方法中调用的update()是给GetBuilder使用的,而导航栏标签用的是Obx,Obx只监听obs变量的变化,update()对它无效。
解决方案

1. 修正控制器中操作obs列表的方式(推荐)

直接调用obs列表自身的add/remove方法,这些方法会自动触发响应式更新,无需手动调用update():

class HomeController extends GetxController {
  // 明确指定泛型,代码更规范
  var filterCountry = <String>[].obs;
  var filterSources = <String>[].obs;

  void filterCountryFunc(String e) {
    if (filterCountry.contains(e)) {
      filterCountry.remove(e); // 直接调用obs列表的remove方法
    } else {
      filterCountry.add(e); // 直接调用obs列表的add方法
    }
    // 移除无用的update()
  }

  void filterSourcesFunc(String e) {
    if (filterSources.contains(e)) {
      filterSources.remove(e);
    } else {
      filterSources.add(e);
    }
    // 移除无用的update()
  }
}

2. 可选:统一响应式组件类型

你当前的_sources()和_country()用了GetBuilder,可以换成Obx来统一响应式逻辑,避免混用导致的更新不一致:

Widget _sources() {
  return Obx(() => ListView(
    children: _syncChannels
        .map((e) => CustomCheckBoxListTile(
              value: homeController.filterSources.contains(e),
              title: Text(e),
              onTap: (newVal) {
                homeController.filterSourcesFunc(e);
              },
            ))
        .toList(),
  ));
}

Widget _country() {
  return Obx(() => ListView(
    children: sourcesController.mapSelectedChannelCheckList.keys
        .map((e) => CustomCheckBoxListTile(
              value: homeController.filterCountry.contains(e),
              title: Text(e.toString()),
              onTap: (newVal) {
                homeController.filterCountryFunc(e);
              },
            ))
        .toList(),
  ));
}
关键知识点
  • obs集合(List/Map/Set)必须调用自身的add/remove/clear等方法,才会触发响应式更新;直接操作.value的方法属于原地修改,不会触发监听。
  • Obx依赖obs变量的变化,GetBuilder依赖update()触发更新,尽量避免两种响应式方式混用。

内容的提问来源于stack exchange,提问作者Hammas Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 14:54:24