【问题标题】:Storing user input as array in Firebase using Flutter使用 Flutter 在 Firebase 中将用户输入存储为数组
【发布时间】:2021-04-08 17:28:37
【问题描述】:

在我的 Flutter 项目中,我有一个表单,用户可以在其中填写详细信息并上传图片。当按下“提交”按钮时,带有以下信息的文档将存储在“产品”集合中,即 Firestore。但是,由于用户能够上传多个图像,我希望将imageUrl 存储为“图像”数组中的字符串元素,而不是“图像”的绝对字符串值,但我不知道该怎么做。目前负责上传上述数据的代码如下:

Future<void> addProduct() {
      // Call the user's CollectionReference to add a new product
      return _firebaseAuthServices.productsReference
          .add({
        'name': nameController.text,
        'size': sizeController.text,
        'price': priceController.text,
        'description': descController.text,
        'images': imageUrl,
      })
          .then((value) => print("Product Added"))
          .catchError((error) => print("Failed to add product: $error"));
    }

如何将imageUrl 的值存储为“图像”数组的元素?

【问题讨论】:

  • 问题到底出在哪里?你是不是故意使用_authservices?
  • 我编辑了这个问题,使其更加清晰和有凝聚力! _firebaseAuthServices 对存储数据的集合的引用
  • imageUrl添加为动态列表

标签: java android firebase flutter dart


【解决方案1】:

使用它来将项目添加到 firebase 中的列表

Future<void> addProduct() {
      // Call the user's CollectionReference to add a new product
      return _firebaseAuthServices.productsReference
          .add({
        'name': nameController.text,
        'size': sizeController.text,
        'price': priceController.text,
        'description': descController.text,
        'images': FieldValue.arrayUnion([imageUrl]),
      })
          .then((value) => print("Product Added"))
          .catchError((error) => print("Failed to add product: $error"));
    }

但这有一个缺陷,您使用的是.add,所以从技术上讲,您的代码每次使用它时都会添加一个新文档,而不是仅加入新添加的imageUrls。

您可以选择创建List&lt;String&gt; 并将其命名为imageUrl,当您将其提交到firebase 时,它​​将使用您的原始代码'images': imageUrl, 作为列表上传。

如果文档已经存在,并且您想稍后对其进行更新,请使用.update,如下所示:

 Future<void> upDateProductImages() {
          // Call the user's CollectionReference to add a new product
          return _firebaseAuthServices.productsReference.doc(yourDocID)
              .update({
             'images': FieldValue.arrayUnion([imageUrl]),//here you can add it as a single String url, as in your initial question. Just be sure that the document exists, otherwise it'll throw an error, since you can't update what doesn't exist.
          })
              .then((value) => print("Product Updated"))
              .catchError((error) => print("Failed to add product: $error"));
        }

【讨论】:

  • 我现在完全可以看到这是如何工作的,感谢您的帮助。由于我对整个读/写过程缺乏经验,我在脑海中对它进行了不同的可视化,但多亏了你,它变得更清晰了!非常感谢
  • 不客气!还有一个我没有提到的附加属性,它叫做.set,你可以使用.set({merge:true}),但是先把这些写下来然后你可以深入研究。如果你有任何其他问题,我很乐意提供帮助当我可以的时候。编码愉快!
猜你喜欢
  • 1970-01-01
  • 2016-10-22
  • 2014-06-04
  • 1970-01-01
  • 1970-01-01
  • 2018-03-22
  • 2013-07-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多