【发布时间】:2020-04-27 20:38:12
【问题描述】:
我正在使用 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(..) 来代替抛出异常,但使用它来完成事务没有错误。
停止交易的方法是什么?
【问题讨论】:
-
事务处理程序返回
Future<dynamic>。如果该 Future 被拒绝,则该事务被中止。因此,从您的事务处理程序返回Future.error是正确的解决方案。还可以在这里查看 Doug 的回答:stackoverflow.com/a/51986647 为什么你希望它会返回一个错误呢? -
这个运气好吗?我无法拒绝颤动的交易。抛出异常或返回 flutter.error 不会做任何事情。
标签: firebase flutter dart google-cloud-firestore