问题描述
我将两个列表动态转换为一个对象,并且试图弄清楚如何检查其中一个属性是否具有相同的值示例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”,但抛出一个错误说
未为定义方法'where' 类“ 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接口,因此没有“ where”和“ contains”方法。这解释了为什么您的问题中提到了错误。 从实现中,我可以看到GeneralProtectionListModel通过“常规”字段将列表包含实际内容。 因此,实现您想要的目标的最简单方法是将实现更改为
list1Protection.general.where((item) => list2Protection.general.contains(item.id));
尽管您将字段“通用”暴露在外部,但该解决方案并不完美。因此,也许更好的方法是将该实现转移到专用方法GeneralProtectionListModel类本身。