我在 dart 中有一个 map
Map<String, List<ProductItem>> _productItemsMap;
我想过滤并得到一个新的Map<String, List<ProductItem>> _newMap
其中产品项目的 id 与我的条件相同。
我怎样才能在 Dart 中做到这一点?
感谢您的帮助。
最佳答案
这里有几种方法:
使用collection-for创建新的Map
并使用collection-if进行过滤:
var _newMap = {
for (var entry in _productItemsMap.entries)
if (satisfiesCondition(entry.key, entry.value))
entry.key: entry.value,
};
使用Iterable.where
进行过滤并使用Map.fromEntries
创建一个新的Map
:
var _newMap = Map.fromEntries(_productItemsMap.entries
.where((entry) => satisfiesCondition(entry.key, entry.value)));
首先使用 Map.of
复制 Map
,然后删除不需要的项目:
var _newMap = Map.of(_productItemsMap)
..removeWhere((key, value) => !satisifiesCondition(key, value));
关于flutter - 在 dart 中从 ' Map<String,ProductItem>myMap' 过滤并获取新的 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61328969/