由于firebase / firestore不支持查询中的不重复列表,因此我正在寻找一种在客户端上创建不重复列表的方法。这样做的原因是,在我的特定情况下,我必须有多个数据库查询,这有时可能导致返回两个或多个具有相同值的文档(即同一文档)。
我尝试过创建这样的Set
final set = Set<User>.from(_people.map<User>((user) => user));
final distinctList = set.map((user) => user).toList();
/// doesn't work since any duplicate document is a separate instance...
但是,正如Flutter文档中所述,Set类仅将对象视为确实是相同的 instance (而不是具有完全相同的值,这正是我所认为的)我在寻找)。
如何以一种不消耗大量资源的简单方式来执行此操作,例如创建一个单独的列表并遍历整个过程以比较每个条目的字段?
答案 0 :(得分:0)
最直接的方法是将equatable package与User类结合使用。在您的课程中:
import 'package:equatable/equatable.dart';
class User {
final String uid;
final String photoURL;
final String email;
final String displayName;
User({
this.uid,
this.photoURL,
this.email,
this.displayName,
/// the important part.
/// make sure to include all your properties above that you want to check for equality.
@override
List<Object> get props => [
uid,
photoURL,
email,
displayName,
];
}
这有效地覆盖了User类相同实例的内置dart相等性检查。现在,Set类将相等地从firebase / firestore中看到两个User文档,并且结果集将仅包含每个User文档一次。
final set = Set<User>.from(_people.map<User>((user) => user));
final distinctList = set.map((user) => user).toList();
/// list is now only distinct user documents.