【问题标题】:Flutter: How to update data in Firestore using the previous stateFlutter:如何使用以前的状态更新 Firestore 中的数据
【发布时间】:2021-03-14 13:19:43
【问题描述】:

我是 Flutter 的新手,我想知道是否可以使用以前的状态更新 Firestore 中的一个字段。我的文档中有一个counter: 0,我正在尝试将其增加 1 或减少 2。

我怎样才能做到这一点?

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    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)
    

    【讨论】:

    • 这是一个很好的增加值的解决方案,但是如果我需要将值减少 2 怎么办?我也需要这样做
    • 你可以为此做一个负增量。 FieldValue.increment(-50)
    • 太棒了!非常好!
    【解决方案2】:

    在使它工作时遇到问题,接受答案的语法对我不起作用,另外,在无数次热重载之后,它终于开始使用这段代码了(我想,应该重新启动应用程序)。在这里发帖,可能会因为语法上的细微差别而对其他人有所帮助

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-12
      • 2021-10-21
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      • 2021-02-07
      • 2021-02-03
      • 2022-11-17
      相关资源
      最近更新 更多