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

Flutter Dart:如何用map.entries筛选Map中的偶数值?

解决Map.entries提取偶数值的问题

你当前代码返回带null的列表,是因为map回调中不满足条件的条目没有返回值,默认返回null。要得到仅包含偶数值的列表,有两种基于Map.entries的实现方式:

方法一:先筛选后映射(推荐)

先通过where筛选出值为偶数的条目,再用map提取对应的值,避免生成不必要的null:

void main() {
  final myMap = {
    'first': 1,
    'second': 2,
    'three': 3,
    'four': 4,
  };

  List<dynamic> list = myMap.entries
      .where((entry) => entry.value % 2 == 0)
      .map((entry) => entry.value)
      .toList();
  
  print(list); // 输出 [2, 4]
}

方法二:映射后过滤null

基于你原本的代码逻辑,在map之后添加where过滤掉所有null值:

void main() {
  final myMap = {
    'first': 1,
    'second': 2,
    'three': 3,
    'four': 4,
  };

  List<dynamic> list = myMap.entries
      .map((entry) {
        if (entry.value % 2 == 0) return entry.value;
        return null;
      })
      .where((value) => value != null)
      .toList();
  
  print(list); // 输出 [2, 4]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 16:02:12