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

Flutter如何同时遍历两个列表

Flutter 同时遍历两个等长列表渲染的实现方案

方案1:索引循环遍历(无额外依赖,适合简单场景)

直接通过索引同时读取两个列表的对应位置元素,配合扩展运算符...将生成的组件插入到children数组中:

List A = ['Chapter 1','Chapter 2','Chapter 3'];
List B = ['Paragraph 1','Paragraph 2','Paragraph 3'];

// 遍历前校验两个列表长度一致,避免索引越界
assert(A.length == B.length);

children: [
  for (int i = 0; i < A.length; i++) ...[
    Text(A[i]),
    Text(B[i]),
  ]
]

方案2:先配对为组合数据再遍历(可读性高,适合复杂业务场景)

如果配对数据需要多次复用,可以先将两个列表的对应元素组合为统一的对象/Record,再遍历组合后的列表:

// Dart 3+ 可直接使用Record配对
List<(String chapter, String paragraph)> contentList = List.generate(
  A.length, 
  (i) => (chapter: A[i], paragraph: B[i])
);

children: [
  for (final content in contentList) ...[
    Text(content.chapter),
    Text(content.paragraph),
  ]
]

注意事项

如果两个列表长度可能不一致,建议取较短列表的长度作为循环上限,避免索引越界:

import 'dart:math';

// 取两个列表的较小长度作为循环终止条件
int loopLength = min(A.length, B.length);
for (int i = 0; i < loopLength; i++) {
  // 业务逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:27:04