firebase - Flutter Cloud Firestore 插件 : How reject a transaction?

标签 firebase flutter dart google-cloud-firestore

我正在使用 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/

相关文章:

firebase - 这很可能是一种暂时性情况,可以通过回退重试来纠正

firebase - flutter应用程序无法与Firebase云数据库进行交互

flutter - Whats ?? = Dart中的运算符

java - 如何使用 RecyclerView 显示空 View ?

ios - 如何在 Firebase 远程配置中使用字符串而不是 plist 设置默认值?

flutter - Flutter:在无状态小部件中,我收到 “The instance member ' xy',无法在初始化程序中对其进行访问。”在数组xy上使用长度时

web - 使用Angular Dart从浏览器获取地理位置时出错

Dart 聚合物条件模板

security - Flutter/Dart 安全扫描

Firebase Firestore : Is there an equivalent of @SerializedName?