我编写了一个函数,如果列表中存在某个元素,该函数将返回 true。我创建了一个早期版本,其中列表包含“ints”并且工作正常。现在我有一个“复杂”对象的列表,它似乎永远不会检测到该对象是否存在。 这是代码:
bool addNewWordToBufferCarnetList(int? wordId) {
CarnetWords newWord =
CarnetWords(iD: wordId!, wrong: 0, right: 0, mastery: 0);
if (_bufferCarnetList.contains(newWord) == true) {
return false;
} else {
_bufferCarnetList.add(newWord);
notifyListeners();
return true;
}
}
还有其他方法可以查看列表是否包含该对象吗?
最佳答案
正如 pskink 所建议和解释的那样,我必须重写 CarnetWords 类中的 == 运算符才能使“相等”发挥作用。 这是代码:
class CarnetWords {
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
if (runtimeType != other.runtimeType) return false;
return other is CarnetWords && other.iD == iD;
}
@override
int get hashCode => iD.hashCode;
int? iD;
int? wrong;
int? right;
double? mastery;
CarnetWords(
{@required this.iD,
@required this.wrong,
@required this.right,
@required this.mastery});
}
感谢 pskink 的帮助和耐心!
关于list - Flutter Dart List - 如何检查列表是否包含对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67751745/