0

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));

2 Answers 2

5

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')
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.