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

Flutter中如何获取Map内值为true的元素总数量

Flutter 统计Map中值为true的元素数量实现方案

现有示例Map对象如下:

Map<String, bool> _toDos = {
      'case1': true,
      'case2': false,
      'case3': false,
      'case4': false,
      'case5' : false
    };

你可以通过以下几种常见方式实现统计:

  • 方法1:过滤取值后直接取长度(最简洁推荐)
    先通过values属性取出Map中所有的布尔值,用where过滤出值为true的项,直接取返回集合的长度即可:
    int trueCount = _toDos.values.where((bool val) => val).length;
    
  • 方法2:使用fold累加计数
    用fold方法初始化计数为0,遍历每个值时遇到true就累加1:
    int trueCount = _toDos.values.fold(0, (prev, val) => prev + (val ? 1 : 0));
    
  • 方法3:基础遍历计数(新手易理解)
    手动遍历Map的每个键值对,匹配到true就给计数变量+1:
    int trueCount = 0;
    _toDos.forEach((key, value) {
      if (value) trueCount++;
    });
    

以上三种方法最终得到的trueCount就是你需要的统计结果,对于中小体积的Map来说三种方法性能差异极小,可以根据自己的代码风格选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 02:39:03