![](/img/trans.png)
[英]How to find a value from List<Map<String, Object>> in dart(flutter)?
[英]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.