我有物件串列,我需要查看新物件是否已經在串列中。所以,如果串列包含新物件,我會創建條件,它回傳 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 $")]]
uj5u.com熱心網友回復:
除了dart原始資料型別(如字串、int 和 double ==...
這個Favorite類即使你沒有擴展Object類,也是一個Objectindart
所以:
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();
}
現在你剛剛說每個Favorite有相同的班級date.toString()應該是平等的。
您可以在==覆寫方法中設定等于邏輯。(這只是一個例子)。
所以當你寫
Favorite fav1 = Favorite(/* other properties*/);
Favorite fav2 = Favorite(/* other properties*/)
fav1 == fav2
它將查看他們是否具有相同的日期,如果是,則true不然false
現在你寫的演算法應該可以作業了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/512867.html
標籤:细绳扑列表镖哎呀
