gpt4 book ai didi

dart - 如何从 Dart 中的 map 中过滤空值

转载 作者:行者123 更新时间:2023-12-03 02:55:10 24 4
gpt4 key购买 nike

跟随 map ,将两个键值对都设为动态,编写一个逻辑来过滤 Map 中没有我们的所有空值?

除了遍历整个 map 并过滤掉值(遍历整个 map 并获取条目对象并丢弃这些对)之外,还有其他方法吗?

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

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

最佳答案

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

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() 的一部分方法你可以用级联运算符做这样的事情:
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 - 如何从 Dart 中的 map 中过滤空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61870032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com