首页 > 解决方案 > 颤振仅在json不存在时才将数据添加到json

问题描述

我有以下型号

product_model.dart

class ProductModel {
  String status;
  String message;
  List<Results> results;

  ProductModel({this.status, this.message, this.results});

  ProductModel.fromJson(Map<String, dynamic> json) {
    status = json['status'];
    message = json['message'];
    if (json['data'] != null) {
      results = new List<Results>();
      json['data'].forEach((v) {
        results.add(new Results.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['status'] = this.status;
    data['message'] = this.message;
    if (this.results != null) {
      data['data'] = this.results.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Results {
  String id;
  String productCode;
  String category;
  String title;
  String isActive;

  Results(
      {this.id,
      this.productCode,
      this.category,
      this.title,
      this.isActive,
      });

  Results.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    productCode = json['product_code'];
    category = json['category'];
    title = json['title'];
    isActive = json['is_active'];

  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['product_code'] = this.productCode;
    data['title'] = this.title;
    data['category'] = this.category;
    data['is_active'] = this.isActive;
    return data;
  }
}

我有将产品保存到收藏夹的功能。收藏夹将在文件中保存为 json。

import 'package:example/utils/favstorage.dart';
import 'package:example/models/product_model.dart';

class FavoriteProducts {
  FavoritesStorage storage = FavoritesStorage();
  List<ProductModel> favorites = [];

  Future addFavorite(ProductModel products) async {
      favorites.add(products);
      await storage.writeFavorites(favorites);
  }
}

仅当产品不存在时,我才想将产品添加到收藏夹中。如何更新该addFavorite方法,以便如果特定id不存在,则仅继续添加到收藏夹。我是新来的。有人可以帮我吗?

标签: flutter

解决方案


了解您的模型:

  1. ProductModel 有列表
  2. 结果有 id。

如何查看提供的 ProductModel 是否可以添加到收藏夹:

  1. 获取收藏夹列表并查看列表。
  2. 在列表中的每个产品型号中。
  3. 对于每个结果,检查 id 是否与方法提供的 ProductModel 列表中的任何结果相同。
  4. 如果一切都是错误的,请将 ProductModel 添加到收藏夹。

以下是供您参考的代码:

Future addFavorite(ProductModel products) async {
    bool containsId = favorites.any((ProductModel model){
        return model.results.any((Results result){
            return products.results.any((Results resultInProducts) => resultInProducts.id == result.id);
        });
    });

    if(!containsId){
        favorites.add(products);
        await storage.writeFavorites(favorites);
    }
}

我希望这会有所帮助,如有任何疑问,请发表评论。如果此答案对您有帮助,请接受并投票赞成答案。


推荐阅读