Mahesh
Mahesh

Reputation: 1593

How to convert setData to transaction in flutter app?

database
          .collection('details')
          .document(userId)
          .setData(
        {
          "othernames": FieldValue.arrayUnion(
            [
              {
                "name": name,
              },
            ],
          ),
        },
        merge: true,
      );

I don't know to convert this to transaction. The transaction has only set and update.
The document will not be exist and i can't use update.
It has to be created

Upvotes: 0

Views: 81

Answers (1)

linxie
linxie

Reputation: 2167

you mean something like this?

final docRef = Firestore.instance.collection('details').doc()
Firestore.instance.runTransaction((Transaction tx) async {
  DocumentSnapshot docSnapshot = await tx.get(docRef);
  if (docSnapshot.exists) {
    await transaction.update(docRef, {
      'othernames': FieldValue.arrayUnion(
        [
          {
            "name": name,
          },
        ],
      )
    });
  }
});

Upvotes: 1

Related Questions