首页 > 解决方案 > 如何在 Flutter 中为 Firebase 连接设置监听器?

问题描述

所以我试图捕捉一个“无网络”错误。

我正在听这样的 Firestore 中的文档:

final docRef = FirebaseFirestore.instance.collection(kInfoCollection).doc(kInfoDocument);

docSubscription = docRef.snapshots().distinct().listen((_) {});

docSubscription.onData((snapshot) => _processInfo(snapshot))

docSubscription.onError((e, s) {
        final errorMessage = 'Message:\n$e \nThe Stack was:\n$s';
        print('Error $errorMessage');
        throw InfoException(errorMessage);
      });

如您所见,侦听器正在侦听文档,如果捕获到任何错误,则会抛出错误。

但是没有捕获到控制台中显示的这些 Firebase 错误:

Connection 1: encountered error(1:53)
6.26.0 - [Firebase/Firestore][I-FST000001] WatchStream (283fb4118) Stream error: 'Unavailable: Network connectivity changed'
6.26.0 - [Firebase/Firestore][I-FST000001] WatchStream (283fb4118) Stream error: 'Unavailable: DNS resolution failed'
6.26.0 - [Firebase/Firestore][I-FST000001] WatchStream (283fb4118) Stream error: 'Unavailable: DNS resolution failed'
6.26.0 - [Firebase/Firestore][I-FST000001] WatchStream (283fb4118) Stream error: 'Unavailable: failed to connect to all addresses'

我错过了什么吗?

附加信息:我通过在手机上进入飞行模式来模拟这个。否则没有错误。

标签: firebasefluttergoogle-cloud-firestore

解决方案


您可以使用connectivity_plus插件来发现网络连接并相应地捕获这些错误。


推荐阅读