【问题标题】:How to structure collections in Firestore and access them in flutter?如何在 Firestore 中构建集合并在 Flutter 中访问它们?
【发布时间】:2020-10-21 21:26:43
【问题描述】:

我正在尝试使用 Flutter 创建一个社交应用,在该应用中我有用户和他们的帖子,所以在 Firestore 中我创建了 2 个集合,

  1. 用户
  2. 帖子

因此,在用户中,它将包含电子邮件、显示图片、简历等用户数据。为了识别,我在帖子中创建了一个密钥,该密钥将引用帖子所属的用户,如下所示,

现在,当我询问特定帖子时,我还想要一些用户详细信息,例如用户名和显示图片,以便我可以在 UI 中的帖子中显示它,

所以,我想使用 StreamBuilder,因为它会反映所做的任何更改,但如果我正在使用 StreamBuilder,我将无法获取用户详细信息。

我怎样才能做到这一点?

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    根据你的数据模型,你需要做两次查询,第一个是获取用户ID,另一个是获取用户对应的帖子。

    
    final StreamController<List<Post>> _postsController =
          StreamController<List<Post>>.broadcast();
    
      Stream listenToPostsRealTime() {
        // Register the handler for when the posts data changes
        _postsCollectionReference.snapshots().listen((postsSnapshot) {
          if (postsSnapshot.documents.isNotEmpty) {
            var posts = postsSnapshot.documents
                .map((snapshot) => Post.fromMap(snapshot.data, snapshot.documentID))
                .where((mappedItem) => mappedItem.userId == FirebaseAuth.instance.currentUser().uid)
                .toList();
    
            // Add the posts onto the controller
            _postsController.add(posts);
          }
        });
    
        return _postsController.stream;
      }
    
    

    【讨论】:

    • 是的,我会试试看
    【解决方案2】:

    我想推荐你观看这个视频:“How to structure your data”和这个post,记住每次读取数据库都会向你收费,所以如果你要从@收集信息987654324@ 文档 每次检索 Post 时,最好在 Posts 文档中包含来自 Users 文档的重复信息,这样您只需查询您的 Posts 文档。请记住,在 NoSQL 世界中对数据进行非规范化(如复制数据)是一种常见行为。 您的结构可能类似于:

    Posts:
    createdAt: "June 25, 2020"
    description: "New food"
    email: "test@email.com"
    image: "https://example.com/assets/image.jpg"
    
    likes:
    [updatedAt: "June 25,2020", user: likerUser]
    
    user: 
    [ name: posterUser, 
      profile_picture: "https://example.com/assets/posterPicture.jpg",
      profile_url: "https://example.com/profiles/userPoster"]
    

    为了让您的数据在两个文档之间保持同步,我建议您查看this answer

    【讨论】:

      猜你喜欢
      • 2010-11-06
      • 2019-12-01
      • 1970-01-01
      • 2019-11-04
      • 2018-10-29
      • 2020-11-10
      • 2022-07-31
      • 2021-12-12
      • 2020-06-26
      相关资源
      最近更新 更多