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
successSnackBar
does not show - which is what I wantBut I would also like the errorSnackBar
to pop-up too which does not happen
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:
add()
call returns, the data is written locally - even before the Future
completes).Future
and makes your await
statement complete.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:
await
you could implement a time-out mechanism to determine if the call to the server is taking longer than what seems reasonable to you.hasPendingWrites
and isFromCache
properties in its SnapshotMetadata
object.