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

Flutter如何将列表传入函数并通过ListView.builder正确渲染

报错根因

你的代码触发的是列表索引越界错误,核心问题是对Dart List的索引规则理解有误:

  • Dart列表采用0起始索引规则,长度为n的列表,合法索引取值范围是0 ~ n-1,直接用list.length(值为n)作为索引访问元素,必然触发RangeError崩溃
  • 你定义的两个数据源列表长度不一致:entries列表共19个颜色名称,colorCodes列表漏写了Colors.amber,仅18个色值,即使索引写对,渲染到最后一项时依然会越界
  • ListView.builder的itemBuilder回调自带的index参数(代表当前渲染项的序号)完全没有被使用,所有传参都硬编码为越界的length值
  • 自定义的cardColor组件虽然定义了color、title入参,但组件内部完全没有使用这些传入值,依然硬编码用length值取数,入参定义形同虚设
修复后可直接运行的代码
import 'package:flutter/material.dart';

class ColorsPage2 extends StatefulWidget {
  const ColorsPage2({Key? key}) : super(key: key);

  @override
  State<ColorsPage2> createState() => _ColorsPage2State();
}

class _ColorsPage2State extends State<ColorsPage2> {
  final List<String> entries = <String>[
    'Red',
    'Pink',
    'Purple',
    'DeepPurple',
    'Indigo',
    'Blue',
    'LightBlue',
    'Cyan',
    'Teal',
    'Green',
    'LightGreen',
    'Lime',
    'Yellow',
    'Amber',
    'Orange',
    'DeepOrange',
    'Brown',
    'Grey',
    'BlueGrey',
  ];
  final List<MaterialColor> colorCodes = <MaterialColor>[
    Colors.red,
    Colors.pink,
    Colors.purple,
    Colors.deepPurple,
    Colors.indigo,
    Colors.blue,
    Colors.lightBlue,
    Colors.cyan,
    Colors.teal,
    Colors.green,
    Colors.lightGreen,
    Colors.lime,
    Colors.yellow,
    Colors.amber,
    Colors.orange,
    Colors.deepOrange,
    Colors.brown,
    Colors.grey,
    Colors.blueGrey,
  ];
  // 对应色值的十六进制字符串,和上面列表顺序一一对应
  final List<String> hexCodes = <String>[
    'F44336',
    'E91E63',
    '9C27B0',
    '673AB7',
    '3F51B5',
    '2196F3',
    '03A9F4',
    '00BCD4',
    '009688',
    '4CAF50',
    '8BC34A',
    'CDDC39',
    'FFEB3B',
    'FFC107',
    'FF9800',
    'FF5722',
    '795548',
    '9E9E9E',
    '607D8B',
  ];

  Widget cardColor({required MaterialColor color, required String title, required String hexColor, required int order}) {
    return InkWell(
      child: Card(
        color: color,
        child: ListTile(
          textColor: Colors.white,
          title: Text(title),
          subtitle: SelectableText(
              'This Is $order Color , Hex: #$hexColor'),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Color List')),
      body: ListView.builder(
        padding: const EdgeInsets.all(8),
        itemCount: entries.length,
        itemBuilder: (BuildContext context, int index) {
          return cardColor(
            color: colorCodes[index],
            title: entries[index],
            hexColor: hexCodes[index],
            order: index + 1, // 显示序号从1开始计数
          );
        },
      ),
    );
  }
}
关键修改说明
  • 补全colorCodes列表缺失的Colors.amber,新增和列表顺序一一对应的hexCodes数组存储色值字符串,保证三个数据源长度完全一致
  • 所有列表元素取值统一使用itemBuilder提供的index参数,从根源上避免索引越界
  • 重构cardColor组件,所有渲染数据从入参获取,不再写死取值逻辑,组件复用性符合预期
  • 列表显示序号用index + 1计算,符合日常从1开始计数的习惯

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 07:09:18