Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup a listener for Firebase connectivity in Flutter?

So I'm trying to catch a 'No Network' error.

I'm listening to a document in Firestore like this:

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);
      });

So as you can see, the listener is listening to a document and will throw an error if it catches any.

But these Firebase errors as shown in the console wasn't caught:

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'

Am I missing something?

Additional info: I simulate this by going to Airplane mode on my phone. Otherwise there is no error.

like image 255
Zenko Avatar asked Oct 08 '20 08:10

Zenko


1 Answers

You could use the connectivity_plus plugin to discover network connectivity and catch these errors accordingly.

like image 191
cofirazak Avatar answered Oct 08 '22 01:10

cofirazak