首页 > 解决方案 > 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 做到这一点的例子。可能吗?

标签: flutterandroid-studiodart

解决方案


对于这种情况,您可以使用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;
  });

推荐阅读