firebase - 如何在flutter中与firestore没有连接的设备中获取DocumentSnapshot?
问题描述
经过多次尝试,我来到这里,根据文档:
Firestore 为离线功能提供开箱即用的支持。在读取和写入数据时,Firestore 使用自动与服务器同步的本地数据库。Cloud Firestore 功能在用户离线时继续,并在他们重新连接时自动处理数据迁移。
所以,我写了一些代码iniState()
FirebaseFirestore.instance
.collection(AppString.FB_USERS)
.doc(FirebaseAuth.instance.currentUser.uid)
.get()
.then((DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists) {
print('Document exists on the database');
}
else{
print('Document not exists on the database');
}
});
它工作正常。
但是当我关闭我的互联网连接并从最近删除应用程序而不是返回我的应用程序时,它不能离线工作
更正 1
@override
void initState() {
super.initState();
FirebaseFirestore.instance.collection(AppString.FB_USERS).doc(FirebaseAuth.instance.currentUser.uid).get(GetOptions(source: Source.cache)).then((DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists) {
print('Document exists on the database');
}
});
如果我只使用get()
而不是get(GetOptions(source: Source.cache))
比它永远不会返回数据
解决方案
该get()
调用首先尝试从服务器获取最新数据,并且该检查可能需要一些时间才能失败。只有一旦失败,它才会从缓存中返回数据。因此,我预计您需要等待的时间比之前更长。
或者,您可以侦听更新,它会为您提供一个流,该流将立即为您提供文档的本地版本(如果有),然后如果服务器有任何更新,则将再次调用您的代码。
推荐阅读
- typescript - rxjs,我如何分组到一个对象?
- javascript - 将句子中每个单词的首字母大写的函数
- javascript - 如何限制高图表中的数据标签?
- javascript - 在搜索输入字段中获取 db mysql 值并在下拉列表中进行修改
- python-3.x - 移动覆盖重定向的顶级窗口以及允许最小化
- android - 如何正确编写 DiffUtil.Callback 以便 recyclerview 移动动画?
- javascript - Nodejs EJS 中的循环
- java - 如何使用 Java 在 MacOS X Catalina 上打开 Terminal.app 并执行脚本?
- css - CSS:即使添加了媒体查询,移动设备上的 div 仍以与桌面相同的宽度显示
- c++ - (已回答)- 在动态分配数组 C++ 时在默认构造函数中创建不同的随机数