【问题标题】:Firestore increment int value if it is exist with flutter如果存在颤动,Firestore 会增加 int 值
【发布时间】:2020-04-02 00:58:30
【问题描述】:

大家好,我正在尝试开发一个应用程序,但我需要一些帮助我有一个功能我只需要执行如果项目存在于 Firestore 我需要增加它的“数量”值。我已经得到并打印了价值,但我需要一些帮助来检查和增加价值,谢谢

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

这是我的 Firestore 的图片,您可以看到那里有嵌套节点

【问题讨论】:

标签: firebase flutter google-cloud-firestore


【解决方案1】:

如果该字段不存在,这就是您想要增加的值,firebase 将使用 1 的值创建它。我对您问题的检查器部分感到困惑。

Firestore.instance.collection("cart")
.document("LIihBLtbfuJ8Dy640DPd")
.setData({foodItem.name: {"quantity": FieldValue.increment(1)}});

【讨论】:

  • 可能需要:updateData({ 'foodItem.name.quantity': FieldValue.increment(1) }).
  • 它也不起作用,因为它是嵌套节点。
  • 好的,我复制并粘贴了您的代码FieldValue.increment(1) 作品我在我的应用程序中尝试过
  • 它可以工作,但它在创建新数据的节点之外
  • 它并没有完全改变我的价值,它不会影响它
猜你喜欢
  • 2020-07-11
  • 2021-06-25
  • 2020-03-05
  • 2021-11-11
  • 2013-03-16
  • 1970-01-01
  • 2020-03-12
  • 2020-06-19
  • 2023-03-11
相关资源
最近更新 更多