繁体   English   中英

Dart/Flutter - 比较两个列表<object>检查它们是否具有相同的值

[英]Dart/Flutter - Compare two List<object> check if they have the same value

我将我的两个列表动态转换为一个对象,我试图弄清楚如何检查属性之一是否具有相同的值示例 id。

List list1 = [{"id": 2, "name": "test1"},   {"id": 3, "name": "test3"} ]; 

List list2 = [{"id": 2, "name": "test1"} ];

这是我将其转换为 List 对象的方法

var list1Protection = GeneralProtectionListModel.fromJson(list1);
var list2Protection = GeneralProtectionListModel.fromJson(list2);

class GeneralProtectionListModel{
  final List<GeneralProtectionModel> general;
  GeneralProtectionListModel({this.general});

  factory GeneralProtectionListModel.fromJson(List<dynamic> json){
    List<GeneralProtectionModel> general = new List<GeneralProtectionModel>();
     general = json.map((i) => GeneralProtectionModel.fromJson(i)).toList();
    return GeneralProtectionListModel(
      general: general
    );
  }
}

class GeneralProtectionModel{
  final int id;
  final String name;
  GeneralProtectionModel({this.id, this.name});
  factory GeneralProtectionModel.fromJson(Map<String, dynamic> json){
    return GeneralProtectionModel(
      id: json['id'],
      name: json['name']
    );
  }
}

我在将 List 动态转换为 List GeneralProtectionListModel 时没有任何问题

在那之后,我尝试使用“where”和“contains”,但它给我抛出了一个错误说

没有为类“GeneralProtectionListModel”定义方法“contains”。

未为类“GeneralProtectionListModel”定义方法“where”

  list1Protection.where((item) => list2Protection.contains(item.id));

您可以使用package:collection/collection.dart深入比较列表/地图/集合/...

List a;
List b;

if (const DeepCollectionEquality().equals(a, b)) {
  print('a and b are equal')
}

list1Protection 和 list2Protection 属于 GeneralProtectionListModel 类型,它没有实现 Iterable 接口,因此没有“where”和“contains”方法。 这解释了为什么您的问题中提到了错误。 从实现中我看到 GeneralProtectionListModel 用实际内容包装列表 - 通过“general”字段。 因此,实现您要尝试的最简单方法是将实现更改为

 list1Protection.general.where((item) => list2Protection.general.contains(item.id));

这个解决方案并不完美,因为您将字段“一般”暴露在外面。 所以也许更好的方法是将此实现移动到专用方法 GeneralProtectionListModel 类本身。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM