我有对象列表,我需要查看新对象是否已经在列表中。所以,如果列表包含新对象,它将返回false,即使我打印了列表,它包含一个具有新对象的相同数据的对象--可能没有根据对象内部的数据在对象之间进行比较。解决方案是什么,例如,我有这个类:
class Favorite{
final Text date;
final Text time;
final Text source;
final Text destination;
final Text price;
Favorite(this.date, this.time, this.source, this.destination, this.price);
// I used this override to print the data inside the object instead of printing 'instance of favorite' to compare the data
@override
String toString() {
return '[$date, $time, $source, $destination, $price]';
}
}在其他班级:
List<Favorite> list = [];
Favorite favorite = Favorite(
Text(Map<String, dynamic>.from(
snapshot.value as Map)[Consts.pathDateJourney]),
Text(Map<String, dynamic>.from(
snapshot.value as Map)[Consts.pathTimeJourney]),
Text(Map<String, dynamic>.from(
snapshot.value as Map)[Consts.pathSourceCity]),
Text(Map<String, dynamic>.from(
snapshot.value as Map)[Consts.pathDestinationCity]),
Text(Map<String, dynamic>.from(
snapshot.value as Map)[Consts.pathPriceJourney]),);
list.add(favorite);
print(list.contains(favorite)); //returning false
print(list[0] == favorite); //returning false打印列表的输出:
I/flutter (14458): []
I/flutter (14458): [[Text("2022-10-27"), Text("05:00"), Text("Homs"), Text("Hama"), Text("800 $")]]
I/flutter (14458): [[Text("2022-10-27"), Text("05:00"), Text("Homs"), Text("Hama"), Text("800 $")], [Text("2022-10-27"), Text("05:00"), Text("Homs"), Text("Hama"), Text("800 $")]]发布于 2022-10-10 19:04:37
dart语言中的所有对象,除了原始数据类型,如字符串、int和double.不相等,因为没有任何==操作符被重写并设置为它,这还包括列表、映射等集合.
Favorite类即使没有扩展Object类,也是dart中的Object
因此:
Favorite() == Favorite() // false除非您重写它的==运算符来设置两个对象应该被视为相等的时间,如下所示:
class Favorite {
final Text date;
final Text time;
final Text source;
final Text destination;
final Text price;
Favorite(this.date, this.time, this.source, this.destination, this.price);
@override
bool operator ==(Object other) {
return other is Favorite && date.toString() == other.date.toString();
} 现在,您刚刚说过,每个具有相同date.toString()的date.toString()类都应该是相等的。
您可以在== overriden方法中设置您的相等逻辑。(这只是一个例子)。
所以当你写
Favorite fav1 = Favorite(/* properties*/);
Favorite fav2 = Favorite(/* properties*/)
fav1 == fav2 // true它会看到他们是否有相同的日期,如果他们是这样的,那就是true,否则就是false
现在你写的算法应该能用。
https://stackoverflow.com/questions/74019380
复制相似问题