首页 > 解决方案 > 检查列表中对象的可用性 -Dart

问题描述

这是我的课

class TypeId {
   final int id;
   final int type;
   TypeId(this.id, this.type);
}

在主函数中

void main() {
  List<TypeId> typeIds = [
    TypeId(1, 2),
    TypeId(1, 3),
  ];

  TypeId sample = TypeId(1, 3);

  if (typeIds.contains(sample)) {
    print('Its Working');
  } else {
    print('This Sucks');
  }  
}

我不知道为什么它不比较,如果这是错误的,请告诉如何检查

标签: flutterdart

解决方案


必须进行比较,因为对象不一样。

class TypeId {
  final int id;
  final int type;
  TypeId(this.id, this.type);

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
  
    return other is TypeId &&
      other.id == id &&
      other.type == type;
  }

  @override
  int get hashCode => id.hashCode ^ type.hashCode;
}

推荐阅读