Roberto
Roberto

Reputation: 263

Flutter: How to update data in Firestore using the previous state

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?

Upvotes: 2

Views: 1239

Answers (2)

Jan
Jan

Reputation: 357

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

Upvotes: 0

Marcel Dz
Marcel Dz

Reputation: 2714

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)

Upvotes: 4

Related Questions