我有以下问题。有两个带有文章的列表。在下面的示例中,结果显示为false。但是条款是一样的。我认为那是因为这些是不同的对象,如果我在两个列表中都添加article1,那将是正确的。
我也从这个问题上尝试过DeepCollectionEquality.unordered()。equals:
How can I compare Lists for equality in Dart?
但这也让我回到了假。
在我的真实项目中,我有两个带有文章的列表。这些列表未排序,因此一个Article可以是一个列表中的第一条,而具有相同ID和名称的文章可以是另一个列表中的最后一个。但是,如果两个列表具有相同的文章(具有相同的名称和ID),则结果应为true。
var a = List<Article>();
var b = List<Article>();
var article1 = Article(id: "1", name: "Beer");
var article2 = Article(id: "1", name: "Beer");
a.add(article1);
b.add(article2);
print(listEquals(a, b));
最佳答案
如您所说,这些是不同的对象,您需要重写类的equal操作符,如下所示:
class Article {
final String name;
final String id;
const Article({this.id,this.name});
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Article &&
runtimeType == other.runtimeType &&
id == other.id;
@override
int get hashCode => id.hashCode;
}
然后结果将为true,因为id是相同的。
你也可以看看这个包
https://pub.dev/packages/equatable
关于list - Dart将无序列表与对象进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58774722/