【发布时间】:2021-09-30 17:33:39
【问题描述】:
我试图了解 Firestore 何时缓存某些内容。为此,我运行以下代码:我希望第一个 get 具有 isFromCache false 并且我希望第二个 get 来自缓存。
FirebaseFirestore.instance.collection('questions').doc("xyz").get().then((DocumentSnapshot documentSnapshot) {
print("1st: " + documentSnapshot.metadata.isFromCache.toString());
FirebaseFirestore.instance.collection('questions').doc("xyz").get(GetOptions(source: Source.cache)).then((DocumentSnapshot documentSnapshot) {
print("2nd: " + documentSnapshot.metadata.isFromCache.toString());
});
});
但是,当运行这个(飞镖,在 Chrome 中运行)时,我注意到以下日志很明显,文档没有被缓存。这是预期的行为吗?我错过了什么吗?
1st: false
zone.dart:1339 Uncaught [cloud_firestore/unavailable] Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)
at Object.wrapException (http://localhost:41665/main.dart.js:2047:17)
at Object.throwExpression (http://localhost:41665/main.dart.js:2061:15)
at guard_closure0.call$1 (http://localhost:41665/main.dart.js:22924:16)
at _RootZone.runUnary$2$2 (http://localhost:41665/main.dart.js:16321:18)
at _RootZone.runUnary$2 (http://localhost:41665/main.dart.js:16325:19)
at _FutureListener.handleError$1 (http://localhost:41665/main.dart.js:15447:19)
at _Future__propagateToListeners_handleError.call$0 (http://localhost:41665/main.dart.js:15732:49)
at Object._Future__propagateToListeners (http://localhost:41665/main.dart.js:5177:77)
at _Future._completeError$2 (http://localhost:41665/main.dart.js:15577:9)
at _Future__asyncCompleteError_closure.call$0 (http://localhost:41665/main.dart.js:15663:18)
编辑:当添加一个像下面这样的监听器时,我确实得到了“1st: false, 2nd: true”的结果。
FirebaseFirestore.instance.collection('questions').doc("xyx").snapshots().listen((event)
{
print("update received");
});
FirebaseFirestore.instance.collection('questions').doc("xyz").get().then((DocumentSnapshot documentSnapshot) {
print("1st: " + documentSnapshot.metadata.isFromCache.toString());
FirebaseFirestore.instance.collection('questions').doc("xyz").get(GetOptions(source: Source.cache)).then((DocumentSnapshot documentSnapshot) {
print("2nd: " + documentSnapshot.metadata.isFromCache.toString());
});
});
【问题讨论】:
-
您好,请问这对您有帮助吗?:stackoverflow.com/a/60321758/15774177
-
@ZeenathSN 感谢您提供有趣的指针。但我遇到的问题不在于 isFromCache 标志的值,而是文档本身似乎一开始并不在缓存中。