Dart / Flutter-比较两个List <dynamic>,如果它们具有相同的id值

时间:2020-08-28 00:46:39

标签: list flutter dart contains

我有两个List<dynamic>,我想弄清楚如何检查id字段中的值是否相同

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

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

我尝试过此方法,但返回的是假

var isMatch = (list1.toSet().intersection(list2.toSet()).length > 0);

1 个答案:

答案 0 :(得分:-1)

您不能像这样进行比较,因为您不能像Boken所说的那样比较动态,您需要为您的对象创建一个类并实现基本搜索,您可以将list2转换为一个集合以使搜索不那么复杂(包含功能)

void main() {
  List list1 = [
  MyObject(2,"test"),
  MyObject(3,"test1")
];

List list2 = [
  MyObject(4,"test")
];
  
  
  for(int i=0;i<list1.length;i++){
    
    if(list2.contains(list1[i])){
      // do your logic
      print(true);
      break;
    }
    
  }
  
}

class MyObject{
  
  int id;
  String name;
  
  MyObject(int id,String name){
    this.id = id;
    this.name = name;
  }
  
  // redifine == operator
  bool operator ==(o) => (o as MyObject).id == this.id;
  
  
}