【问题标题】:Flutter exclude in futurebuilder items with same idFlutter 在具有相同 id 的 futurebuilder 项目中排除
【发布时间】:2021-05-31 12:14:55
【问题描述】:

我有带有 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 做到这一点的例子。有可能吗?

【问题讨论】:

    标签: flutter android-studio dart


    【解决方案1】:

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

    【讨论】:

    • 看起来不错,但如果商店 ID 是动态的并且有其他重复项?
    • 所以你想删除所有重复的,只保留第一个?
    • 很好的解决方案,谢谢,你用谷歌节省了我的时间
    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    相关资源
    最近更新 更多