嗨,我正在尝试在 Flutter 中使用 Firebase Firestore 实现简单的事务。该过程很简单,只需更新两个文件,如下所示:
DocumentSnapshot productSnapshot = await productReference.get();
DocumentSnapshot userSnapshot = await userReference.get();
DocumentSnapshot userProductSnapshot = await userProductReference.get();
if (productSnapshot.exists &&
userSnapshot.exists &&
userProductSnapshot.exists) {
double price = double.parse(productSnapshot.data["productPrice"].toString());
double money = double.parse(userSnapshot.data["money"].toString());
double afterBuyMoney = money - price;
if (afterBuyMoney >= 0) {
await userReference.updateData({"money": afterBuyMoney});
await userProductReference.updateData(({"isOwned": true}));
response = "success";
}
}
Run Code Online (Sandbox Code Playgroud)
此代码已经运行良好并获得预期结果,并且数据在云数据库中更新,但是因为有两个事务并且中间事务可能存在错误。我想使用 Firestore runTransaction 来实现这个,所以如果出现错误,所有的事务都将被回滚。
这是我使用 Firestore runTransaction 的代码
await Firestore.instance.runTransaction((transaction) async {
DocumentSnapshot productSnapshot = await transaction.get(productReference);
DocumentSnapshot userSnapshot = await transaction.get(userReference); …Run Code Online (Sandbox Code Playgroud)