我正在使用 cloud_firestore 插件编写交易,如果特定数据字段与条件不匹配,我想拒绝交易
final refProdotti = refs.getSubReferences('products');
final refOrdini = refs.getSubReferences('orders');
return refs.db.runTransaction((trans) async {
for(var productOrder in order.prodotti) {
var refProdotto = refProdotti.document(productOrder.prodottoId);
print(productOrder.prodottoId);
var docProdotto = await trans.get(refProdotto);
var oldQuantita = docProdotto.data['quantity'];
if(oldQuantita < productOrder.quantita){
throw docProdotto.data['nome'] + ' not available';
}
//aggiorno la quantità nella collezione prodotto
var newQuantita = oldQuantita - productOrder.quantita;
await trans.update(refProdotto, { 'quantity': newQuantita });
}
}
问题是,当我抛出异常时,我得到一个 PlatformException(在事务中读取的每个文档也必须在该事务中写入。,null)。
我尝试使用 Future.error(..) 而不是抛出异常,但使用该事务完成没有错误。
停止交易的方法是什么?
最佳答案
这有点晚了,但您可以尝试抛出 FirebaseException 来终止事务。
import 'package:cloud_firestore/cloud_firestore.dart';
...
try {
FirebaseFirestore firestore = FirebaseFirestore.instance;
await firestore.runTransaction((transaction) async {
...
throw FirebaseException(plugin: 'cloud_firestore', code: 'predefined-condition-failed');
...
});
} on FirebaseException catch (e) {
if (e.code == 'predefined-condition-failed') {
// Do something
}
...
}
...
关于firebase - Flutter Cloud Firestore 插件 : How reject a transaction?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59677546/