Home > Software design >  checking if querysnapshot has made a connection to the firestore
checking if querysnapshot has made a connection to the firestore

Time:11-05

When a certain document exists I want to go to another page then when a document does not exist. The code below does well when the app user has connection. However, when the connection to the internet is lost, the function will always return that it could not find the query. What I want to do is let the function give an error when it could not connect to the firestore so I can stay on the same page and try again.

Thank you in advance!

Future<bool> checkIfDocExists({String? id}) async {
  var snapshot = await FirebaseFirestore.instance
      .collection('rentals')
      .where('DeviceID', isEqualTo: id)
      .where('Status', isEqualTo: 0)
      .get();
  return (snapshot.docs.isNotEmpty);
}

CodePudding user response:

In this case you should check device internet connection. There is a package to help you to check internet status.

connectivity_plus => https://pub.dev/packages/connectivity_plus

connectivity => https://pub.dev/packages/connectivity

Code sample :

  ConnectivityResult? _connectivityResult;
 
  Future<void> _checkConnectivityState() async {
    final ConnectivityResult result = await Connectivity().checkConnectivity();
 
    if (result == ConnectivityResult.wifi) {
      print('Connected to a Wi-Fi network');
    } else if (result == ConnectivityResult.mobile) {
      print('Connected to a mobile network');
    } else {
      print('Not connected to any network');
    }
 
    setState(() {
      _connectivityResult = result;
    });
  }

You can check internet connection before read document from firestore.

CodePudding user response:

If you want to make sure the document is read from the server, you can specify a source option for that:

...
.get(GetOptions(source: Source.server));

With this option the call will fail when it can't read the document from the server.

Also see the FlutterFire reference documentation for Source.

  • Related