Firestore and caching



我试图理解当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());
});
});

然而,当运行这个(dart,在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)

编辑:当添加像下面这样的侦听器时,我确实得到了&;1:false, 2: 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());
});
});

您正在根据代码发出标准请求,并期望从缓存中提供服务,这是对缓存工作方式的误解。

启用离线访问是缓存所必需的,并且在文档中指出,只有当设备处于离线模式并且文档处于缓存中时才返回fromache。

最新更新