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

Flutter使用List.generate生成列表时如何为点击的3个随机项分配随机颜色

实现步骤

你需要把原来存储选中索引的列表,替换为存储「索引-对应随机色」的映射表,这样每个选中项可以绑定独立的颜色,具体修改如下:


1. 替换State类中的变量定义

把原来的List _clicked和单一Color _color替换为以下变量:

// 随机数实例
final Random _random = Random();
// 键为选中的容器索引,值为对应的随机颜色
Map<int, Color> _selectedColors = {};

2. 修正点击事件逻辑

你原有代码存在两处笔误:ListView(listLength, (index)应为List.generate(9, (index),_clicked.add(in)应为_clicked.add(index),修正后的onTap逻辑如下,默认最多选中3个容器,每个分配独立随机色:

onTap: () {
  setState(() {
    if (_selectedColors.containsKey(index)) {
      // 已选中则移除选中状态
      _selectedColors.remove(index);
    } else {
      // 最多选中3个,超过数量不处理
      if (_selectedColors.length < 3) {
        // 生成随机RGB颜色赋值
        _selectedColors[index] = Color.fromRGBO(
          _random.nextInt(256),
          _random.nextInt(256),
          _random.nextInt(256),
          1,
        );
      }
    }
  });
},

如果你的需求是点击任意容器后,自动随机选中3个不同的容器并分别赋值随机色,则把onTap逻辑替换为以下内容即可:

onTap: () {
  setState(() {
    // 先清空之前的选中状态
    _selectedColors.clear();
    // 生成3个不重复的随机索引
    final selectedIndexes = <int>{};
    while (selectedIndexes.length < 3) {
      selectedIndexes.add(_random.nextInt(9));
    }
    // 给每个选中索引分配随机颜色
    for (var idx in selectedIndexes) {
      _selectedColors[idx] = Color.fromRGBO(
        _random.nextInt(256),
        _random.nextInt(256),
        _random.nextInt(256),
        1,
      );
    }
  });
},

3. 修改容器颜色的取值逻辑

把原有代码中_isSelected ? _color : Colors.white替换为从映射表中取值:

color: _selectedColors.containsKey(index) ? _selectedColors[index]! : Colors.white,

完整修正后的代码

GridView(
  shrinkWrap: true,
  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisSpacing: 2,
    mainAxisSpacing: 2,
    crossAxisCount: 3,
  ),
  children: List.generate(9, (index) {
    return Center(
      child: GestureDetector(
        onTap: () {
          setState(() {
            if (_selectedColors.containsKey(index)) {
              _selectedColors.remove(index);
            } else {
              if (_selectedColors.length < 3) {
                _selectedColors[index] = Color.fromRGBO(
                  _random.nextInt(256),
                  _random.nextInt(256),
                  _random.nextInt(256),
                  1,
                );
              }
            }
          });
        },
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 400),
          curve: Curves.easeInQuad,
          decoration: BoxDecoration(
            border: Border.all(
                style: BorderStyle.solid, color: Colors.black),
            color: _selectedColors.containsKey(index) ? _selectedColors[index]! : Colors.white,
          ),
        ),
      ),
    );
  }),
),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 17:54:03