仅当数据不存在时才向json添加数据

时间:2020-01-08 16:35:56

标签: flutter

我有以下型号

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不存在,则只能继续添加到收藏夹。 我是新来的扑扑。有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

您可以使用andindexWhere在列表中搜索具有相同ID的商品,例如:

Future addFavorite(ProductModel products) async {
  if(favorites.indexWhere((listProduct) => listProduct.id == products.id) == -1){
    favorites.add(products);
    await storage.writeFavorites(favorites);
  }
}

-1表示没有项目,如果有该项目,它将从列表中返回。

答案 1 :(得分:1)

了解您的模型:

  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);
    }
}

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