如何从Dart地图中过滤空值 [英] how to filter null values from map in Dart

查看:264
本文介绍了如何从Dart地图中过滤空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

跟随地图,将两个键值对都设为动态,编写逻辑以在没有我们的情况下从Map过滤掉所有空值?

Following the map, having both key-value pair as dynamic, Write a logic to filter all the null values from Map without us?

还有其他方法吗?而不是遍历整个地图并过滤出值(遍历整个地图并获取Entry Object并丢弃那些对)?

Is there any other approach than traversing through the whole map and filtering out the values (Traversing whole map and getting Entry Object and discarding those pairs) ?

我需要删除所有为null并返回地图

Map<String, dynamic> toMap() {
 return {
  'firstName': this.firstName,
  'lastName': this.lastName
};


推荐答案

使用 removeWhere on 映射删除要过滤的条目:

Use removeWhere on Map to remove entries you want to filter out:

void main() {
  final map = {'text': null, 'body': 5, null: 'crap', 'number': 'ten'};

  map.removeWhere((key, value) => key == null || value == null);

  print(map); // {body: 5, number: ten}
}

如果将此操作作为 toMap()方法的一部分,您可以使用级联运算符执行以下操作:

And if you want to do it as part of your toMap() method you can do something like this with the cascade operator:

void main() {
  print(A(null, 'Jensen').toMap()); // {lastName: Jensen}
}

class A {
  final String firstName;
  final String lastName;

  A(this.firstName, this.lastName);

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'firstName': this.firstName,
      'lastName': this.lastName
    }..removeWhere(
        (dynamic key, dynamic value) => key == null || value == null);
  }
}

这篇关于如何从Dart地图中过滤空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆