flutter - Flutter 在具有相同 id 的 futurebuilder 项目中排除
问题描述
我有带有 json 数据的 api:
{
"@id": "/products/622",
"@type": "Product",
"id": 622,
"ppStoreId": "",
"slug": "",
"bgColor": "#ffffff",
"image": "1aa10b2b5a99c63292b11db3bce9669955afa7ed.jpg",
"name": "",
"descriptionAz": null,
"descriptionEn": null,
"descriptionRu": null,
"views": 1,
"ppRating": null,
"expected": false,
"active": true,
"fixedPrice": false,
"tags": [],
"category": {
"@id": "/categories/22",
"@type": "Category",
"id": 22,
"slug": "",
"bgColor": "#000000",
"icon": "acd57416324ef2f00da0aa460077b76637403015.svg",
"nameAz": "",
"nameEn": "",
"nameRu": ""
},
"store": "34"
}
我需要排除或隐藏具有相同商店 id 34 的项目,但只需要先显示。我还没有找到一个如何用 Flutter 做到这一点的例子。可能吗?
解决方案
对于这种情况,您可以使用fold方法。遍历所有项目,并且仅在其没有商店 id 34 或者它是第一个具有 id 34 的商店时才添加项目。
final List<Map<String, dynamic>> noDuplicateData = jsonData
.fold(<Map<String, dynamic>>[],
(List<Map<String, dynamic>> previous, Map<String, dynamic> current) {
// Check if store id is not 34 or if it is the first one
if (current['store'] != 34 ||
!previous.any((data) => data['store'] == '34')) {
previous.add(current);
}
return previous;
});
要仅获取第一个副本,您可以这样做。
final List<Map<String, dynamic>> noDuplicateData = jsonData
.fold(<Map<String, dynamic>>[],
(List<Map<String, dynamic>> previous, Map<String, dynamic> current) {
if (!previous.any((data) => data['store'] == current['store'])) {
previous.add(current);
}
return previous;
});
推荐阅读
- java - 应用程序重新启动,由于 AndroidRuntime 异常而无法运行
- c# - WPF:如何使用 C# 设置属性 Helptext
- angular - 如何在 Typescript(Angular) 中将类型实现为对象的值
- php - SQL 查询 SET & Update 但未从 PHP 调用
- vba - 从 MS Access VBA 使用 Shape.DrawSpline 方法 (Visio)
- perl - Perl CGI 元标记视口
- javascript - 在 Pusher 中不会收到任何警报消息
- javascript - Node.js 问题添加包
- ruby-on-rails - 将 json hash 转换为 rails 上的键
- javascript - angular.copy 不复制具有子对象或数组的对象