1

I have a firebase object that a user increments but can't increment to a certain number. I want to have a condition in the transaction to prevent the user from incrementing past a set number. How do I cancel the transaction and return an error to the user i.e

    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;
      });

Shei
  • 393
  • 4
  • 15
  • [From a previous question](https://stackoverflow.com/questions/52091895/firebase-how-to-break-realtime-database-transaction-with-different-state-message) – cpboyce Apr 06 '21 at 13:37
  • @cpboyce That does not use dart (Flutter) – Shei Apr 06 '21 at 13:42
  • Correct, it uses JS. I was adding it as a reference where you can apply the same principles to dart. – cpboyce Apr 06 '21 at 13:45
  • Adding `return` creates an error since you are not returning anything and adding null as in `return null` to the return throws a warning `The getter 'value' was called on null.` – Shei Apr 06 '21 at 13:47

1 Answers1

0

Adding the transactionResult handlers seems to work


     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';
        }
      }


Shei
  • 393
  • 4
  • 15