0
votes

I'm using this function - which adds a document to my Firestore :

Future<void> addUser() {
  // Call the user's CollectionReference to add a new user
  return users
      .add({
        'full_name': fullName, // John Doe
        'company': company, // Stokes and Sons
        'age': age // 42
      })
      .then((value) => print("User Added"))
      .catchError((error) => print("Failed to add user: $error"));
}

I would like to display a successful SnackBar() when data has been successfully added to Firestore

& an error SnackBar() when data failed to being added to Firestore

How do i do so ?


Here is my SnackBar :

ScaffoldMessenger.of(context).showSnackBar(successSnackBar);
2

2 Answers

2
votes

You can use like this

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

or you can use below expression

try {
  
} on FirebaseException catch (e) {

}

Moreover, Your function return type is Future void and you are returning Firebase instant. That is not accurate. Remove the return keyword in for Future<void> type function and make it asynchronies as shown below,

Future<void> addUser() async {
   await .....
}
1
votes

The above answer is good I just suggest removing previous snackbars before showing a new one.

ScaffoldMessenger.of(context).hideCurrentSnackBar(); 
ScaffoldMessenger.of(context).removeCurrentSnackBar();
ScaffoldMessenger.of(context).clearSnackBars();

You can choose one from above methods and do like this :

ScaffoldMessenger.of(context)
            ..hideCurrentSnackBar()
            ..showSnackBar(snackBar);