skip to Main Content

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',
  );

2

Answers


  1. Try this:

    await FirebaseFirestore.instance((transaction) async {
       await transaction.update(usersRef.doc('foo_id'),{
         'name' : 'John'
       });
    });
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search