Flutter中Firestore无网络连接时如何获取DocumentSnapshot?
经过多次尝试后我来到此处咨询,根据官方文档说明:
Firestore默认支持离线能力,读写数据时Firestore会使用本地数据库自动与服务端同步。用户离线时Cloud Firestore功能仍可正常使用,恢复网络连接后会自动处理数据同步。
我在initState()中编写了如下代码:
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)),将始终无法返回数据。
内容的提问来源于stack exchange,提问作者Vora Ravi
相关产品推荐
相关产品推荐

