【问题标题】:Flutter Cloud Firestore Plugin: How reject a transaction?Flutter Cloud Firestore 插件:如何拒绝交易?
【发布时间】: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&lt;dynamic&gt;。如果该 Future 被拒绝,则该事务被中止。因此,从您的事务处理程序返回 Future.error 是正确的解决方案。还可以在这里查看 Doug 的回答:stackoverflow.com/a/51986647 为什么你希望它会返回一个错误呢?
  • 这个运气好吗?我无法拒绝颤动的交易。抛出异常或返回 flutter.error 不会做任何事情。

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

这有点晚了,但您可以尝试抛出 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
   }
   ...
}
...

【讨论】:

    猜你喜欢
    • 2018-04-04
    • 2020-07-30
    • 1970-01-01
    • 2019-03-20
    • 2021-12-05
    • 2021-01-06
    • 2014-09-03
    • 2015-06-21
    • 2014-02-10
    相关资源
    最近更新 更多