'Flutter Firebase Realtime Database write/update to multiple nodes at once

I'm using Firebase as the backend to my Flutter project. I need to write to multiple nodes in one transaction. Now I have:

await (_firebaseDatabase
        .reference()
        .child('user_data').Push().set({"userName":"aaa"}));
await (_firebaseDatabase
        .reference()
        .child('user_history').Push().set({"userName":"aaa"}));

But these are 2 transactions, so 1 could end successfully but another one could fail and I want to prevent this.

Another use case is to write to user_data and update to user_history. How can we achieve this in a firebase real-time database?

Basically, I want to insert and update at 2 different nodes in a single transaction so that data doesn't get mismatched.



Solution 1:[1]

What you are looking for is known as a multi-path write operation, which allows you to write to multiple, non-overlapping paths with a single update call. You can specify the entire path to update for each key, and the database will then set the value you specify at that specific path.

To generate two separate unique keys, you can call push() twice without any arguments. When called like that, it doesn't actually write to the database, but merely generates a unique reference client-side, that you can then get the key from.

Combined, it would look something like this:

const db = _firebaseDatabase.reference();
const key1 = db.push().key;
const key2 = db.push().key;
const values = {};
values["user_data/"+key1+"/username"] = "aaa";
values["user_history/"+key2+"/username"] = "aaa";
db.update(values);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frank van Puffelen