Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use .updateData() instead of .setData() in flutter firestore even when document does not exist

I am trying to do something along the lines that, if there does not exist a document then do setData and if the document exist, do update data... I have tried this(the code below), it seems to work but I am concerned that what if when I launch the app and the error message changes.

Future updateReference(
    String phoneNumber,
  ) async {
    try {
      return await mCollectionRef.document(phoneNumber).updateData({
        uid: true,
      });
    } on PlatformException catch (error) {
      print(error.message.substring(0, 9));
      if (error.message.substring(0, 9) == 'NOT_FOUND') {
        return await mCollectionRef.document(phoneNumber).setData({
          uid: true,
        });
      }
    }
  }

Is there any other way in which I can achieve this?

like image 693
Sarvesh Bhatnagar Avatar asked Oct 31 '25 11:10

Sarvesh Bhatnagar


1 Answers

If you want to update or create a document if it doesn't already exist, you can just pass merge: true as the second argument to setData().

like image 192
Doug Stevenson Avatar answered Nov 02 '25 13:11

Doug Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!