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

Flutter:如何将两个数组传入FlSpot构建List<FlSpot>

解决方案

你可以通过以下几种方式将两个数组分别作为FlSpot的x、y值来构建目标列表:

方法一:索引循环遍历

通过遍历列表索引,依次取出对应位置的x和y值创建FlSpot:

List<FlSpot> spots = [];
for (int i = 0; i < dateTimeDouble.length; i++) {
    // 避免索引越界,仅当unitsList对应位置有值时添加
    if (i < unitsList.length) {
        spots.add(FlSpot(dateTimeDouble[i], unitsList[i]));
    }
}

方法二:使用List.generate(更简洁)

利用List.generate方法直接生成列表,同时处理长度不一致的情况:

// 需要先导入math包:import 'dart:math';
int validLength = math.min(dateTimeDouble.length, unitsList.length);
List<FlSpot> spots = List.generate(validLength, (index) {
    return FlSpot(dateTimeDouble[index], unitsList[index]);
});

注意事项

  • 优先确保dateTimeDouble和unitsList的长度一致,否则会有部分数据无法匹配;如果长度不一致,建议先做校验(比如抛出异常或提示),避免数据丢失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 02:52:00