Dart中如何判断自定义类的对象是否存在于List中
问题原因
Dart中自定义类默认的相等判断是引用相等,即只有两个变量指向内存中同一个实例时,==判断才会返回true。你代码中创建的TypeId(1,3)和列表里的TypeId(1,3)是两个完全独立的实例,内存地址不同,因此默认==判断为不等,contains方法默认依赖==做相等校验,所以会返回false。
解决方案
方案1:重写自定义类的==运算符和hashCode(推荐规范做法)
如果你的自定义类需要支持按属性判断相等,按照Dart规范必须同时重写==运算符和hashCode,修改后的TypeId类代码如下:
class TypeId { final int id; final int type; TypeId(this.id, this.type); // 重写==,按两个属性判断相等 @override bool operator ==(Object other) => identical(this, other) || other is TypeId && runtimeType == other.runtimeType && id == other.id && type == other.type; // 重写hashCode,用两个属性的hash值组合 // Dart 2.14以下版本写法 @override int get hashCode => id.hashCode ^ type.hashCode; // Dart 2.14及以上版本可以用更简便的写法 // @override // int get hashCode => Object.hash(id, type); }
修改后再运行你原有main函数的代码,contains就会返回true,正常输出Its Working。
方案2:直接遍历列表手动匹配属性(无需修改类定义)
如果只是临时需要判断、不想改动类的定义,可以使用列表的any方法手动校验属性:
void main() { List<TypeId> typeIds = [ TypeId(1, 2), TypeId(1, 3), ]; TypeId sample = TypeId(1, 3); // 手动匹配两个属性 if (typeIds.any((element) => element.id == sample.id && element.type == sample.type)) { print('Its Working'); } else { print('This Sucks'); } }
这个方法不需要修改原有类的代码,适合一次性校验的场景。
内容的提问来源于stack exchange,提问作者M O N I S H
相关产品推荐
相关产品推荐

