【问题标题】:Flutter upload list to Google FirestoreFlutter 上传列表到 Google Firestore
【发布时间】:2019-08-20 10:53:36
【问题描述】:

我想将我的 Flutter 测试应用中的列表添加到我的 Google Firestore。

这是我的方法,它添加了所有数据:

void postToFireStore(
{String mediaUrl, String location, String description}) {

var reference = Firestore.instance.collection('insta_posts');

  reference.add({
    "marked_friends": [chipstuete.toString()],
    "username": currentUserModel.username,
    "location": location,
    "likes": {},
    "mediaUrl": mediaUrl,
    "description": description,
    "ownerId": googleSignIn.currentUser.id,
    "timestamp": new DateTime.now().toString(),

    }).then((DocumentReference doc) {
    String docId = doc.documentID;
    reference.document(docId).updateData({"postId": docId});
  });
}

一切正常,期待列表“marked_friends”...

列表“chipstuete”有多个字符串:

[马丁·苏伯特、莉娜·赫斯勒、费雯·琼斯]

但我的 Firestore 看起来像这样:

目前整个列表存储在marked_friends[0]...

我需要更改什么,我的列表“chipstuete”的每个条目都存储在 Firestore 中我的数组“marked_friends”的单独字段中?

最好的问候!

【问题讨论】:

  • 删除toString() 和括号? firestore api 将为您序列化它们。 "marked_friends": chipstuete 应该可以正常工作
  • 那个不行,我之前试过。 Firestore 中没有创建新文档,控制台显示:“未处理的异常:无效参数:'AppProfile' 的实例”......这就是我尝试将列表项转换为字符串的原因。
  • 这是因为自动序列化仅适用于核心 dart 类型,如 intboolList 等。对于自定义类型,您需要自己序列化它们

标签: list firebase arraylist flutter google-cloud-firestore


【解决方案1】:

您必须在AppProfile 类中添加一个将其序列化为List 的方法。

所以在你的AppProfile 类中:

class AppProfile {

  ... // Whatever fields/methods you have

  // Add this method
  List<String> getFriendList() {
    // Somehow implement it so it returns a List<String> based on your fields
    return ['name1','name2','name3'];
  }
}

那你就可以了

"marked_friends": chipstuete.getFriendList(),

【讨论】:

  • 谢谢!关于如何实施的任何想法?你推荐“chipstuete.forEach”吗?
  • 我不知道你的 AppProfile 类包含什么,所以我不能真正告诉你具体如何。看起来你只是想保存一个朋友列表,所以我想你会有一个包含所有用户朋友姓名的 friends 字段?如果是这种情况,您可以将其退回。
【解决方案2】:

我有办法。

就像 SwiftingDuster 说的,我需要一种将它序列化为 List 的新方法:

List<String> toList() {

  chipstuete.forEach((item) {
    newtuete.add(item.toString());
  });

  return newtuete.toList();
}

之后我只需在我的 postToFirestore() 方法中调用 toList() 并添加 "marked_friends": newtuete.而已!

【讨论】:

    猜你喜欢
    • 2020-06-28
    • 2018-12-05
    • 2020-09-24
    • 2021-09-19
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    相关资源
    最近更新 更多