You need to enable JavaScript to run this app. Flutter/Dart开发如何实现9个按钮中仅单个按钮选中高亮的效果
优惠活动
大模型
产品
解决方案
定价
更多

Flutter/Dart开发如何实现9个按钮中仅单个按钮选中高亮的效果

实现单选效果的修改方案

无需修改MyButtonModal类,只需调整点击事件的逻辑,每次点击时先重置所有按钮的选中状态,再处理当前点击的按钮状态即可。

两种可选效果实现

1. 支持取消选中(点击已选中的按钮可取消,允许无按钮选中)

修改onTap回调的逻辑如下:

onTap: () {
  setState(() {
    // 先记录当前按钮的原有状态
    bool currentSelected = f.changeButtonColor;
    // 遍历所有按钮,全部重置为未选中
    for (var btn in _a) {
      btn.changeButtonColor = false;
    }
    // 如果原来未选中,就设为选中;原来已选中的话保持重置后的未选中状态
    if (!currentSelected) {
      f.changeButtonColor = true;
    }
  });
}

2. 必须选中一个(始终有一个按钮处于选中状态,点击已选中按钮无反应)

修改onTap回调的逻辑如下:

onTap: () {
  setState(() {
    // 遍历所有按钮,全部重置为未选中
    for (var btn in _a) {
      btn.changeButtonColor = false;
    }
    // 直接把当前点击的按钮设为选中
    f.changeButtonColor = true;
  });
}

完整修改后的GridView代码示例(以支持取消选中的版本为例)

GridView.count(
  shrinkWrap: true,
  physics: ClampingScrollPhysics(),
  mainAxisSpacing: 10,
  crossAxisSpacing: 10,
  childAspectRatio: 80 / 95,
  crossAxisCount: 12,
  children: _a.map((MyButtonModal f) {
    return InkWell(
      child: Container(
          decoration: BoxDecoration(
              color: f.changeButtonColor
                  ? Colors.blue
                  : Colors.white,
              borderRadius: BorderRadius.circular(5),
              border: Border.all(color: Color(0xffaaaaaa))),
          child: Center(
            child: Text(f.buttonText),
          )),
      onTap: () {
        setState(() {
          bool currentSelected = f.changeButtonColor;
          for (var btn in _a) {
            btn.changeButtonColor = false;
          }
          if (!currentSelected) {
            f.changeButtonColor = true;
          }
        });
      },
    );
  }).toList()),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 06:15:05