【发布时间】:2021-03-14 13:19:43
【问题描述】:
我是 Flutter 的新手,我想知道是否可以使用以前的状态更新 Firestore 中的一个字段。我的文档中有一个counter: 0,我正在尝试将其增加 1 或减少 2。
我怎样才能做到这一点?
【问题讨论】:
标签: firebase flutter dart google-cloud-firestore
我是 Flutter 的新手,我想知道是否可以使用以前的状态更新 Firestore 中的一个字段。我的文档中有一个counter: 0,我正在尝试将其增加 1 或减少 2。
我怎样才能做到这一点?
【问题讨论】:
标签: firebase flutter dart google-cloud-firestore
Firestore 对此有一个特定的运算符,称为 FieldValue.increment()
文档: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)
});
如果你想减少使用负值:
FieldValue.increment(-50)
【讨论】:
在使它工作时遇到问题,接受答案的语法对我不起作用,另外,在无数次热重载之后,它终于开始使用这段代码了(我想,应该重新启动应用程序)。在这里发帖,可能会因为语法上的细微差别而对其他人有所帮助
Future<void> updateStreakOnCorrect(String docId) async {
DocumentReference collection = FirebaseFirestore.instance.collection("sentences").doc(docId);
collection.update({"streak": FieldValue.increment(1)});
}
【讨论】: