首页 > 解决方案 > 如何在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))比它永远不会返回数据

标签: firebasefluttergoogle-cloud-firestore

解决方案


get()调用首先尝试从服务器获取最新数据,并且该检查可能需要一些时间才能失败。只有一旦失败,它才会从缓存中返回数据。因此,我预计您需要等待的时间比之前更长。

或者,您可以侦听更新,它会为您提供一个流,该流将立即为您提供文档的本地版本(如果有),然后如果服务器有任何更新,则将再次调用您的代码。


推荐阅读