如何在Dart中过滤Map中空值

zpgglvta  于 2022-12-25  发布在  其他
关注(0)|答案(7)|浏览(396)

跟随Map,使两个键-值对都是动态的,编写一个逻辑来过滤Map中的所有空值而不使用我们?
除了遍历整个Map并过滤掉值(遍历整个Map并获取Entry Object,然后丢弃这些对)之外,还有其他方法吗?

我需要删除所有空值并返回map

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

0h4hbjxa1#

Map上使用removeWhere删除要过滤掉的条目:

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()方法的一部分,你可以用cascade运算符来做类似这样的事情:

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

class A {
  final String? firstName;
  final String? lastName;

  A(this.firstName, this.lastName);

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

lnlaulya2#

现在,您可以将Map文字与条件条目一起使用:

Map<String, dynamic> toMap() => {
  if (firstName != null) 'firstName': firstName,
  if (lastName != null) 'lastName': lastName,
};
8xiog9wr

8xiog9wr3#

我这样做是为了使用removeWhere更容易地从maplist中删除空值:https://dartpad.dartlang.org/52902870f633da8959a39353e96fac25
样品:

final data = 
  {
    "name": "Carolina Ratliff",
    "company": null,
    "phone": "+1 (919) 488-2302",
    "tags": [
      "commodo",
      null,
      "dolore",
    ],
    "friends": [
      {
        "id": 0,
        "name": null,
        "favorite_fruits": [
          'apple', null, null, 'pear'
        ]
      },
      {
        "id": 1,
        "name": "Pearl Calhoun"
      },
    ],
  };

void main() {
  // From map
  print('Remove nulls from map:\n' + data.removeNulls().toString());
  // From list
  print('\nRemove nulls from list:\n' + [data].removeNulls().toString());
}
taor4pac

taor4pac4#

    • removeWhere**的局限性在于它不检查嵌套值。如果要删除层次结构中的所有键,请使用此递归解决方案。
dynamic removeNull(dynamic params) {
    if (params is Map) {
      var _map = {};
      params.forEach((key, value) {
        var _value = removeNull(value);
        if (_value != null) {
          _map[key] = _value;
        }
      });
      // comment this condition if you want empty dictionary
      if (_map.isNotEmpty)
        return _map;
    } else if (params is List) {
      var _list = [];
      for (var val in params) {
        var _value = removeNull(val);
        if (_value != null) {
          _list.add(_value);
        }
      }
      // comment this condition if you want empty list
      if (_list.isNotEmpty)
        return _list;
    } else if (params != null) {
      return params;
    }
    return null;
  }

示例:

void main() {
    Map<String, dynamic> myMap = {
      "a": 1,
      "b": 2,
      "c": [
        3,
        4,
        null,
        {"d": 7, "e": null, "f": 5}
      ],
      "g": {"h": null, "i": null},
      "j": 6,
      "h": []
    };
    print(removeNull(myMap));
  }

输出:

{a: 1, b: 2, c: [3, 4, {d: 7, f: 5}], j: 6}

注:

如果在map和list的子元素具有空值时需要空的map和list,请在代码中注解掉map和list的空检查。

quhf5bfb

quhf5bfb5#

建议使用removeWhere函数

Map<String, dynamic> map = {
      '1': 'one',
      '2': null,
      '3': 'three'
    };

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

vulvrdjw6#

也许,就像我所做的,有人可能会来寻找,如何从一个模型中删除空字段,该模型将使用retrofit和dio in flutter发送到API下面是我用来从Model对象中删除空值的方法
@正文(空到不存在:正确)
例如

@POST("/shops")
Future<Shop> createShop(@Body(nullToAbsent: true) Shop shop);

*nullToAbsent参数就能解决问题 *

relj7zay

relj7zay7#

这是我在Flutter 3中使用的方法:

Map<String, Object?> removeAllNulls(Map<String, Object?> map) {
  final data = {...map};
  data.removeWhere((key, value) => value == null);
  for (final entry in data.entries.toList()) {
    final value = entry.value;
    if (value is Map<String, Object?>) {
      data[entry.key] = removeAllNulls(value);
    } else if (value is List<Object?>) {
      final list = List.from(value);
      for (var i = 0; i < list.length; i++) {
        final obj = list[i];
        if (obj is Map<String, Object?>) {
          list[i] = removeAllNulls(obj);
        }
      }
      data[entry.key] = list;
    }
  }
  return data;
}

用法:

var jsonData = jsonDecode(jsonEncode(example.toJson()));
jsonData = removeAllNulls(jsonData);

相关问题