【问题标题】:Add data from flutter to firestore with array format使用数组格式将数据从flutter添加到firestore
【发布时间】:2021-12-26 02:49:44
【问题描述】:

目前我的颤振代码正在将数据添加到像图 1 这样的 Map 类型的 Firestore。 image 1 但是,我希望它以图像 2 的数组类型将数据添加到 firestore。 image2 这是在 Map 类型中将点击的项目添加到 firestore 数据库的代码(图 3) Image 3

【问题讨论】:

  • 尝试将变量_items 直接添加到firestore,即。不要将其转换为地图

标签: firebase flutter google-cloud-firestore


【解决方案1】:

您似乎想要向 Firestore 添加类似于 Array of Maps 的内容。基于这个另一个thread,它是不费吹灰之力就可以做到的。我已经确认它适用于我的测试 Firestore 并使用了以下代码:

//Adding new array of maps

Map<String, dynamic> user1 = {"firstName": "Jane", "lastName": "Smith"};
Map<String, dynamic> user2 = {"firstName": "John", "lastName": "Doe"};

FirebaseFirestore firestore = FirebaseFirestore.instance;
firestore
  .collection('testMapArray')
  .doc('test1')
  .update({
    'array1': [user1, user2]
  })
  .then((value) => print("Updated"))
  .catchError((error) => print("Failed"));

这是它在 Firestore 浏览器中的外观:

您还可以使用FieldValue.arrayUnion() function 将其他值附加到数组而不更改现有值:

 //Adding additional elements to the array of maps

  Map<String, dynamic> user1 = {"firstName": "Jane", "lastName": "Smith"};
  Map<String, dynamic> user2 = {"firstName": "John", "lastName": "Doe"};
  Map<String, dynamic> user3 = {"firstName": "Foo", "lastName": "Bar"};

  FirebaseFirestore firestore = FirebaseFirestore.instance;
  firestore
      .collection('testMapArray')
      .doc('test1')
      .update({
        'array1': FieldValue.arrayUnion([user3])
      })
      .then((value) => print("Updated"))
      .catchError((error) => print("Failed"));

这个 sn-p 只将第三个用户添加到现有的地图数组中:

【讨论】:

  • 如果此答案对您有所帮助,您可以单击复选标记图标将其标记为已接受。这可以帮助遇到同样问题的未来用户。
猜你喜欢
  • 1970-01-01
  • 2021-01-08
  • 2020-08-09
  • 2021-06-23
  • 1970-01-01
  • 2020-09-12
  • 2023-03-24
  • 2019-04-25
  • 1970-01-01
相关资源
最近更新 更多