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

Flutter多容器点击差异化设置背景色问题求助(新手)

解决方案

你当前的问题核心是只用了单个颜色变量,无法区分四个容器的选中状态。要实现点击目标容器变红、其余容器变蓝的效果,只需通过一个变量记录选中容器的索引即可,具体实现如下:

  1. 在你的State类中添加一个用于记录选中索引的变量:
int? selectedIndex; // 初始值为null,表示未选中任何容器
  1. 为每个容器绑定对应的索引,点击时更新选中状态并刷新UI:
// 以Row布局四个容器为例,你也可以根据需求换成Column或其他布局
Row(
  mainAxisAlignment: MainAxisAlignment.spaceAround,
  children: [
    // 第一个容器
    GestureDetector(
      onTap: () {
        setState(() {
          selectedIndex = 0;
        });
      },
      child: Container(
        width: 80,
        height: 80,
        color: selectedIndex == 0 ? Colors.red : Colors.blue,
        alignment: Alignment.center,
        child: Text('S1'),
      ),
    ),
    // 第二个容器
    GestureDetector(
      onTap: () {
        setState(() {
          selectedIndex = 1;
        });
      },
      child: Container(
        width: 80,
        height: 80,
        color: selectedIndex == 1 ? Colors.red : Colors.blue,
        alignment: Alignment.center,
        child: Text('S2'),
      ),
    ),
    // 第三个容器
    GestureDetector(
      onTap: () {
        setState(() {
          selectedIndex = 2;
        });
      },
      child: Container(
        width: 80,
        height: 80,
        color: selectedIndex == 2 ? Colors.red : Colors.blue,
        alignment: Alignment.center,
        child: Text('S3'),
      ),
    ),
    // 第四个容器
    GestureDetector(
      onTap: () {
        setState(() {
          selectedIndex = 3;
        });
      },
      child: Container(
        width: 80,
        height: 80,
        color: selectedIndex == 3 ? Colors.red : Colors.blue,
        alignment: Alignment.center,
        child: Text('S4'),
      ),
    ),
  ],
)

如果想简化代码,也可以用List.generate批量生成容器,效果完全一致:

Row(
  mainAxisAlignment: MainAxisAlignment.spaceAround,
  children: List.generate(4, (index) {
    return GestureDetector(
      onTap: () {
        setState(() {
          selectedIndex = index;
        });
      },
      child: Container(
        width: 80,
        height: 80,
        color: selectedIndex == index ? Colors.red : Colors.blue,
        alignment: Alignment.center,
        child: Text('S${index + 1}'),
      ),
    );
  }),
)

这样处理后,点击任意容器时,该容器会显示红色,其余三个自动切换为蓝色,完全满足你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 14:02:45