【发布时间】:2020-04-22 10:41:20
【问题描述】:
我正在使用以下内容从 Firestore 返回一个流:
Stream<CompletedExerciseList> getExerciseStream(String uid, {int limit}) {
Stream<QuerySnapshot> snapshots;
try {
CollectionReference exerciseCollection = Firestore.instance.collection('users').document(uid).collection('completed_exercise');
if (limit != null) {
snapshots = exerciseCollection.orderBy('startTime', descending: false).orderBy('name', descending: true).limit(limit).snapshots();
} else {
snapshots = exerciseCollection.orderBy('startTime', descending: false).orderBy('name', descending: true).snapshots();
}
} catch (e) {
print(e);
}
return snapshots.map((list) => CompletedExerciseList(list.documents.map((doc) => ExerciseModel.fromMap(doc.data)).toList()));
}
上述方法在小部件构建时返回一个流,但是当集合中的文档更新时,流不会更新。但是,如果我删除 orderBy 子句,当从集合中添加/删除文档时,流会正确更新。所以下面的代码可以工作,但是我需要能够对快照的结果进行排序和限制。
Stream<CompletedExerciseList> getExerciseStream(String uid, {int limit}) {
Stream<QuerySnapshot> snapshots;
try {
CollectionReference exerciseCollection = Firestore.instance.collection('users').document(uid).collection('completed_exercise');
if (limit != null) {
snapshots = exerciseCollection.limit(limit).snapshots();
} else {
snapshots = exerciseCollection.snapshots();
}
} catch (e) {
print(e);
}
return snapshots.map((list) => CompletedExerciseList(list.documents.map((doc) => ExerciseModel.fromMap(doc.data)).toList()));
}
对于这两种情况,我的控制台都不会打印错误。我正在使用带有 Flutter SDK 的 Android Studio。
【问题讨论】:
-
控制台不会给出错误,例如,当您使用 order by 时,需要使用链接创建索引的链接?当您订购时,使用多个字段进行过滤时,必须创建一个复合索引。 firebase.google.com/docs/firestore/query-data/…
-
我认为需要索引,但我没有在控制台日志中收到错误消息。
-
我相信您正在使用 StreamBuilder,如果您检查 snapshot.hasError 并打印错误,您应该会在此处收到错误消息。如果没有,一旦使用,future 来执行相同的查询而不是流并调用该 future 应该会给出错误
-
您需要使用集合id“completed_exercise”为“startTime”和“name”这两个字段创建复合索引
-
如果我将
.limit(1)添加到我的 firestore 快照查询中,则不会调用 Stream 的监听函数。请分享您的建议,如果有的话。谢谢。
标签: firebase flutter dart google-cloud-firestore