Search code examples
flutterfirebasegoogle-cloud-firestore

How to run transaction in cloud_firestore_odm?


I want to run a transaction to update data in the Cloud Firestore using cloud_firestore_odm.

This code works fine:

usersRef 
  .doc('foo_id')
  .update(
    name: 'John',
  );

But this one doesn't. I'm doing something wrong, can anyone tell me how to properly do it?

final transaction = await FirebaseFirestore.instance.runTransaction((_) async => _);

usersRef 
  .doc('foo_id')
  .transactionUpdate(
    transaction,
    name: 'John',
  );

Solution

  • Due to how the ODM works, the syntax for using transactions using the Firestore ODM is slightly different.

    Instead of:

    await FirebaseFirestore.instance.runTransaction((transaction) async {
      transaction.update(usersRef.doc('id'), {'age': 42});  
    });
    

    You should do:

    await FirebaseFirestore.instance.runTransaction((transaction) async {
      usersRef.doc('id').transactionUpdate(transaction, age: 42);  
    });
    

    Basically, the transaction vs "reference" are swapped. But as a benefit, the transaction object is fully typed.

    The same logic applies for any other transaction method.