【问题标题】:How to cancel Flutter RealTime Database Transactions如何取消 Flutter 实时数据库事务
【发布时间】:2021-07-02 04:10:10
【问题描述】:

我有一个用户递增但不能递增到某个数字的 firebase 对象。 我想在交易中有一个条件,以防止用户增加超过设定的数字。 如何取消交易并向用户返回错误,即

    try {

    int setLimit = 12; //example limit... Can vary

    final TransactionResult transactionResult = await myRef.runTransaction((MutableData mutableData) async {
        var currentValue = mutableData.value ?? 0;
        if (currentValue >= setLimit) {
          throw 'full'; // .... how do I return from this (return throws error ... Expects MutableData)
        }
        mutableData.value = (mutableData.value ?? 0) + 1;
        return mutableData;
      });

【问题讨论】:

  • @cpboyce 不使用飞镖(颤振)
  • 正确,它使用 JS。我将它添加为参考,您可以将相同的原则应用于飞镖。
  • 添加 return 会产生错误,因为您没有返回任何内容并将 return null 中的 null 添加到返回中会引发警告 The getter 'value' was called on null.

标签: firebase flutter firebase-realtime-database


【解决方案1】:

添加 transactionResult 处理程序似乎可以工作


     int setLimit = 12;


     final TransactionResult transactionResult = await myRef.runTransaction((MutableData mutableData) async {
        var currentValue = mutableData.value ?? 0;
        if (currentValue >= setLimit) {
          throw 'full';
        }
        mutableData.value = (mutableData.value ?? 0) + 1;
        return mutableData;
      });

      if (transactionResult.committed) {
        return transactionResult.dataSnapshot.value;
      } else {
        if (transactionResult.error != null) {
          return transactionResult.error.details;
        } else {
          return 'full';
        }
      }


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-23
    • 2021-04-08
    • 2021-03-04
    • 2022-08-20
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 2011-07-18
    相关资源
    最近更新 更多