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

Flutter中如何统计嵌套列表的总元素数量?

统计Flutter嵌套列表的总元素数量

你遇到的问题是因为List本身没有sum方法,而且即便有,直接调用也不会自动遍历嵌套的子列表去统计长度。下面给你几种可行的实现方式:

方法一:使用fold方法(简洁推荐)

fold可以帮我们从初始值开始,逐个累加每个子列表的长度:

List<dynamic> days = [[1, 3, 4, 6], [1, 2, 3]];
int totalCount = days.fold(0, (total, sublist) => total + (sublist as List).length);
print(totalCount); // 输出7

因为你的列表是List<dynamic>,所以需要把每个子列表强转为List来获取长度;如果能提前确定子列表类型,建议把days定义为List<List<int>>,这样就不用类型转换了,代码更安全。

方法二:遍历累加

用forEach逐个遍历子列表,手动累加长度:

List<dynamic> days = [[1, 3, 4, 6], [1, 2, 3]];
int totalCount = 0;
days.forEach((sublist) {
  totalCount += (sublist as List).length;
});
print(totalCount); // 输出7

方法三:借助collection包的扩展方法

如果你的项目里导入了collection包,可以先把每个子列表的长度转成新列表,再用扩展的sum方法:

import 'package:collection/collection.dart';

List<dynamic> days = [[1, 3, 4, 6], [1, 2, 3]];
int totalCount = days.map((sublist) => (sublist as List).length).sum;
print(totalCount); // 输出7

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:25:53