简体   繁体   中英

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

I convert my two list dynamic to an object and I am trying to figure it out how can I check if one of the attribute has the same value example id.

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

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

Here's how I convert it to List object

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

I don't have any problem on conversion the List dynamic to List GeneralProtectionListModel

after that I am trying to use the 'where' and 'contains' but it throws me an error says that

The method 'contains' isn't defined for the class 'GeneralProtectionListModel'.

The method 'where' isn't defined for the class 'GeneralProtectionListModel'

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

You can use package:collection/collection.dart to deeply compare lists/maps/sets/...

List a;
List b;

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

list1Protection and list2Protection are of type GeneralProtectionListModel, which does not implement Iterable interface, thus has no "where" and "contains" methods. This explains why you have errors mentioned in your question. From implementation I see that GeneralProtectionListModel wraps list with actual contents though - through "general" field. So the simplest way to echieve what you are tryig to to is to change implementation to

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

This solution is not perfect though as you expose field "general" outside. So maybe better approach would be to move this implementation to dedicated method GeneralProtectionListModel class itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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