Advertisement

TrimwebsolutionsTrimwebsolutions

Problem and Solutions

Is there a way to avoid a Firestore field from reaching a negative value in android ?

By M.K. Verma · 4 May 2022

Is there a way to avoid a Firestore field from reaching a negative value in android ?

I could solve it! And if you have the same problem, here's how. I went the way round and used a transaction instead of FieldValue.update()

Basically, I did the following:

void update() async {
    await FirebaseFirestore.instance.runTransaction((transaction) async {
      final snapshot = await transaction.get(docRef);
      final amount = snapshot.get("example");
      if (amount > 0) {
        final newAmount = snapshot.get("example") - 1;
        transaction.update(docRef, {"example": newAmount});
      }
    });
  }