firebaseflutterdartgoogle-cloud-firestore

Writing to FireStore - how to show error when fails (if no network)


I'm writing data to Firestore Using this function - which works perfectly

  Future<void> validateForm() async {
    try {
      await FirebaseFirestore.instance.collection('collectionPath').add({
        'full_name': 'John Doe',
        'company': 'Stokes and Sons',
        'age': '42',
      });
      ScaffoldMessenger.of(context).showSnackBar(successSnackBar);
    } catch (e) {
      print(e.toString());
      ScaffoldMessenger.of(context).showSnackBar(errorSnackBar);
    }
  }

but I'm trying to display a SnackBar when data can't be written to FireStore

But I would also like the errorSnackBar to pop-up too which does not happen


Solution

  • Not having a network connection to the backend is not an error condition for Firestore clients. In such situations they simply commit the write locally, fire all necessary events, and synchronize up with the server once a connection is available.

    So the usual order of events is:

    The only times your catch will get called is actually when that local write operation fails, or when the write gets rejected on the server (typically because it violates your security rules). In all other cases, there is (intentionally) no error thrown.

    You have a few options: