2

I'm new in Flutter and I want to know if there is a way to update one field in Firestore using its previous state. I have like a counter: 0 in my document, and I'm trying to increment it by one or decrement it by 2.

How can I achieve this?

0

2 Answers 2

4

Firestore has a specific operator for this called FieldValue.increment()

Documentation: https://firebase.google.com/docs/firestore/manage-data/add-data#increment_a_numeric_value

var washingtonRef = db.collection('cities').doc('DC');

// Atomically increment the population of the city by 50.
washingtonRef.update({
    population: firebase.firestore.FieldValue.increment(50)
});

If you want to decrement use a negative value:

FieldValue.increment(-50)
Sign up to request clarification or add additional context in comments.

3 Comments

This is a pretty good solution for incrementing the value, but what if I need to decrement by 2 the value? I need to do that too
You can just do a negative increment for that. FieldValue.increment(-50)
Awesome!! Very nice!
0

Had issues with making it work, syntax of the accepted answer didn't work for me, plus, after countless times of hot reload, it finally started to work with this code (I presume, should restart the app). Posting here, maybe it helps others because of slight syntax differences

  Future<void> updateStreakOnCorrect(String docId) async {
    DocumentReference collection = FirebaseFirestore.instance.collection("sentences").doc(docId);
    collection.update({"streak": FieldValue.increment(1)});
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.