1

hi guys i am trying to develop an app but i need some help i have a function i just need to do if item is exist on firestore i need to increment "quantity" value of it. i already got and printing the value but i need some help for checker and incrementing value thanks

String checker = await Firestore.instance
        .collection('cart')
        .document('LIihBLtbfuJ8Dy640DPd')
        .get()
        .then((DocumentSnapshot ds) => ds.data[foodItem.name]);
    if (checker == foodItem.name) {
      await Firestore.instance
          .collection('cart')
          .document('LIihBLtbfuJ8Dy640DPd')
          .get()
          .then((DocumentSnapshot ds) =>
              a = ds.data[foodItem.name]['quantity']);

      Firestore.instance
          .collection("cart")
          .document("LIihBLtbfuJ8Dy640DPd")
          .updateData({
        foodItem.name: {'quantity': q++}
      });
    } else {
      Firestore.instance.runTransaction((Transaction transaction) async {
        await transaction.update(
            Firestore.instance
                .collection("cart")
                .document("LIihBLtbfuJ8Dy640DPd"),
            {
              foodItem.name: {
                'itemName': foodItem.name,
                'imgUrl': foodItem.imageAssetPath,
                'itemPrice': foodItem.price,
                'quantity': q,
              }
            });
      });
    }

enter image description here this is picture of my firestore as you can see there is nested nodes there

  • Does this answer your question? [Firestore Increment FieldValue](https://stackoverflow.com/questions/54543067/firestore-increment-fieldvalue) – Shady Boshra Apr 02 '20 at 01:45

1 Answers1

2

This is what you want to increment a value if the field doesn't exist firebase will create it with the value of 1. I am confused as to the checker part of your question.

Firestore.instance.collection("cart")
.document("LIihBLtbfuJ8Dy640DPd")
.setData({foodItem.name: {"quantity": FieldValue.increment(1)}});
wcyankees424
  • 2,554
  • 2
  • 12
  • 24