You need to enable JavaScript to run this app. Flutter如何使用GetX实现点击ListTile仅更改选中项的文字颜色
优惠活动
大模型
产品
解决方案
定价
更多

Flutter如何使用GetX实现点击ListTile仅更改选中项的文字颜色

Flutter 实现ListTile点击仅选中项修改文字颜色方案

问题根源

你当前的实现逻辑中,控制器仅维护了一个全局的isSelected布尔状态,所有列表项的样式都绑定了这同一个状态变量,因此点击任意项都会触发全量列表项的样式同步变更,无法实现单个选中项的独立控制。


单选场景实现(同一时间仅一个项可选中)

控制器修改代码

// 存储当前选中项的索引,初始值-1代表无选中项
RxInt selectedIndex = (-1).obs;

// 切换选中状态,接收当前点击项的索引作为入参
void toggle(int index) {
  selectedIndex.value = selectedIndex.value == index ? -1 : index;
}

ListView 修改代码

ListView.builder(
  itemCount: _antigen.plantAntigens.length,
  itemBuilder: (BuildContext cntxt, int index) {
    return ListTile(
      title: Text(
        _antigen.plantAntigens[index],
        style: TextStyle(
          // 仅当前索引匹配选中索引时显示红色
          color: controller.selectedIndex.value == index ? Colors.red : Colors.black87
        ),
      ),
      onTap: () {
        // 点击时传入当前项的索引
        controller.toggle(index);
      });
  },
),

多选场景实现(可同时选中多个项)

控制器修改代码

// 存储所有选中项的索引集合
RxSet<int> selectedIndexes = <int>{}.obs;

void toggle(int index) {
  if (selectedIndexes.contains(index)) {
    selectedIndexes.remove(index);
  } else {
    selectedIndexes.add(index);
  }
}

ListView 样式判断修改

只需要调整Text的style判断逻辑即可:

style: TextStyle(
  color: controller.selectedIndexes.contains(index) ? Colors.red : Colors.black87
),

内容的提问来源于stack exchange,提问作者Aman Rawat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 14:09:00