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

Flutter实现ListView.builder内仅选中按钮修改背景色

原因

你当前所有按钮共用了同一个全局颜色变量_color,修改该变量会同步作用到所有按钮的样式配置上,因此点击任意按钮都会触发所有按钮背景色变更。

实现方案

我们只需将存储颜色的单一变量改为存储当前选中项的索引即可,默认值设为-1代表无选中项。

第一步:修改变量定义

List<String> items = ['A', 'B', 'C'];
// 替换原来的_color变量,存储当前选中的按钮索引
int _selectedIndex = -1; 

第二步:修改ListView.builder逻辑

每个按钮渲染时判断当前索引是否匹配选中索引,匹配则使用蓝色背景,否则使用透明背景;点击时更新选中索引为当前点击的索引即可。

ListView.builder(
  itemCount: items.length,
  itemBuilder: (context, index) {
    return ElevatedButton(
      style: ButtonStyle(
        backgroundColor: MaterialStateProperty.all(
          _selectedIndex == index ? Colors.blue : Colors.transparent
        )
      ),
      onPressed: () {
        setState(() {
          _selectedIndex = index;
          // 如果需要支持点击已选中按钮取消选中,替换上面一行为:
          // _selectedIndex = _selectedIndex == index ? -1 : index;
        });
      },
      child: Text(items[index]),
    );
  },
);

内容的提问来源于stack exchange,提问作者Kucing Malaya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:12:00