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

Flutter开发中如何从颜色列表为行/容器分配对应颜色

解决方案

核心修改思路

  • 遍历单元格时获取当前行索引,按行索引匹配预设颜色列表中的对应颜色
  • 通过取模运算处理行数超过颜色列表长度的场景,避免下标越界
  • 适配你后续要添加顶部列名的需求,提前预留了列名插入位置

修改后完整代码

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Rows and Columns Matrix'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // 预设颜色列表移到State层,避免每次build重复创建
  final List<Color> manyColors = [
    Colors.red,
    Colors.green,
    Colors.blue,
    Colors.yellow,
    Colors.brown,
    Colors.purple,
    Colors.orange,
    Colors.pink
  ];

  @override
  Widget build(BuildContext context) {
    List<List<int>> numbers = [];
    List<int> columnNumbers = [];
    int z = 1;
    int numberOfTubes = 18;

    for (int i = 0; i < numberOfTubes; i++) {
      int fibersPerTube = 24;
      for (int y = 0; y < fibersPerTube; y++) {
        int currentNumber = z + y;
        columnNumbers.add(currentNumber);
      }
      z += fibersPerTube;
      numbers.add(columnNumbers);
      columnNumbers = [];
    }

    final myRowChildren = numbers.asMap().entries.map((columnEntry) {
      int columnIndex = columnEntry.key;
      List<int> columnValues = columnEntry.value;
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 顶部列名容器,不需要可以直接删除这段
          Container(
            padding: EdgeInsets.all(2),
            decoration: BoxDecoration(
              color: Colors.grey[200],
              border: Border.all(color: Colors.black, width: 1),
            ),
            child: Text(
              '列${columnIndex + 1}',
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
          ),
          // 原有光纤数值单元格
          ...columnValues.asMap().entries.map((rowEntry) {
            int rowIndex = rowEntry.key;
            int nr = rowEntry.value;
            return Container(
              padding: EdgeInsets.all(2),
              decoration: BoxDecoration(
                // 按行索引取颜色,取模实现循环配色
                color: manyColors[rowIndex % manyColors.length],
                border: Border.all(
                  color: Colors.black,
                  width: 1,
                ),
              ),
              child: Text(
                nr.toString(),
              ),
            );
          }).toList()
        ],
      );
    }).toList();

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: SingleChildScrollView(
          // 新增垂直滚动适配行数过多的场景
          scrollDirection: Axis.vertical,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: myRowChildren,
          ),
        ),
      ),
    );
  }
}

关键改动说明

  • 将manyColors从build方法移到State类中,减少不必要的重复初始化
  • 使用asMap().entries.map替代原有的普通map,获取单元格对应的行、列索引
  • 配色逻辑改为manyColors[rowIndex % manyColors.length],实现按行配色、超出颜色数量自动循环的效果
  • 新增了顶部列名容器,直接修改Text内容即可自定义列名,不需要可以删除对应代码段
  • 新增垂直滚动能力,适配行数过多时的显示需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 06:36:02