飞镖/颤振 - 比较两个列表检查<object>它们是否具有相同的值



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

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

以下是我如何将其转换为列表对象

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 dynamic转换为List GeneralProtectionListModel 方面没有任何问题

在那之后,我试图使用"where"one_answers"contains",但它给了我一个错误,说

没有为类定义方法'contains'"GeneralProtectionListModel"。

没有为class"GeneralProtectionListModel">

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接口,因此没有"其中";以及";包含";方法。这就解释了为什么你的问题中提到了错误。从实现中,我看到GeneralProtectionListModel通过";一般的";领域因此,最简单的方法就是将实现更改为

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

这种解决方案并不完美,尽管当您暴露字段";一般的";外部所以,也许更好的方法是将这个实现转移到专用的方法GeneralProtectionListModel类本身。

最新更新