-1

I am trying to create an social app using flutter, in that app I have users and their posts, so in firestore I am creating 2 collections,

  1. Users
  2. Posts

So, in users it will have user data like email, display picture, bio etc. For identification I'm creating a key in posts which will have a reference to the user to whom the post belongs, like so,

Collections

Now, I while I ask a particular post I also want some of the user details like UserName and display picture so that I can show it in the Post in the UI like,

post

So, I want to use StreamBuilder as it will reflect any changes made, but I can't get user details if I'm using StreamBuilder.

How can I achieve this?

Tushar Patil
  • 748
  • 4
  • 13

2 Answers2

0

According to your data model, you need to make two queries, the first one to get the user ID and others to get the posts corresponding to the user.


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

Aditya Joshi
  • 1,033
  • 7
  • 20
0

I would like to recommend you to visit this video: "How to structure your data" and this post, remember that you will be charged for every read to the database, so if you're going to gather information from the Users document every time you retrieve a Post, it would be a better idea to have duplicated information from the Users document inside your Posts document, this way you only have to query your Posts document. Remember that denormalizing data (like replicating it) on the NoSQL world is a common behaviour. Your structure could be something similar to:

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"]

In order to keep your data synced between both documents I recommend you to check this answer

Emmanuel
  • 1,436
  • 1
  • 11
  • 17