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

Flutter ListView.builder如何循环复用短于项数的颜色列表为ListTile设背景色

Flutter ListTile 循环复用固定颜色列表设置背景色方案

核心实现逻辑:利用取模运算实现固定颜色列表的循环复用,既可以避免数组索引越界,也完全匹配你需要的循环配色效果。

核心修改点

  • 原代码中tileColor: colors[index]替换为tileColor: colors[index % colors.length]

index % colors.length会将任意正整数index映射到0到colors.length-1的范围内,你使用的颜色列表长度为4,所以计算出的索引会循环输出0、1、2、3、0、1、2、3……,刚好对应红、黄、蓝、绿的循环配色需求。

修改后完整代码

import 'package:flutter/material.dart';

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

List<Color> colors = [Colors.red, Colors.yellow, Colors.blue, Colors.green];

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: 8,
        itemBuilder: (BuildContext context, int index) {
          return ListTile(
              tileColor: colors[index % colors.length],
              title: Text("List item $index")
          );
        }
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 00:06:06