skip to Main Content

Okay so my profile posts are working as intended right here, I am showing the users posts that only they have made to their very own profile
enter image description here

Now here is the code doing that

  static Future<List<Post>> getUserPosts(String currentUserId) async {
    QuerySnapshot userPostsSnap = await postsRef
        .doc(currentUserId)
        .collection('userPosts')
        .orderBy('timestamp', descending: true)
        .get();
    List<Post> userPosts =
        userPostsSnap.docs.map((doc) => Post.fromDoc(doc)).toList();
    return userPosts;
  }

and also to show them to the profile page as you see in the image:

showProfilePosts(UserModel author) {
    return Expanded(
      child: ListView.builder(
          shrinkWrap: true,
          physics: AlwaysScrollableScrollPhysics(),
          itemCount: _allPosts.length,
          itemBuilder: (context, index) {
            return PostContainer(
              post: _allPosts[index],
              author: author,
              currentUserId: widget.currentUserId,
            );
          }),
    );
  }

  getAllPosts() async {
    List<Post> userPosts =
        await DatabaseMethods.getUserPosts(widget.visitedUserId);
    if (mounted) {
      setState(() {
        _allPosts = userPosts;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    getAllPosts();
  }

now my goal is to show every single post made by every user (I’m creating one big forum) so how can I show every single post made by everyone in the database to my home screen? My database also looks like this for some visuals, would I have to loop through?
enter image description here

here is my Home screen’s code, where I wish to display every users posts

class HomeScreen extends StatefulWidget {
  final String currentUserId;

  const HomeScreen({Key? key, required this.currentUserId}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  List _homeScreenPosts = [];
  bool _loading = false;

  buildHomeScreenPosts(Post post, UserModel author) {
    return PostContainer(
      post: post,
      author: author,
      currentUserId: widget.currentUserId,
    );
  }

  showHomeScreenPosts(String currentUserId) {
    List<Widget> homePostsList = [];
    for (Post post in _homeScreenPosts) {
      homePostsList.add(
        FutureBuilder(
          future: usersRef.doc(post.authorId).get(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (snapshot.hasData) {
              UserModel author = UserModel.fromSnap(snapshot.data);
              return buildHomeScreenPosts(post, author);
            } else {
              return SizedBox.shrink();
            }
          },
        ),
      );
    }
    return homePostsList;
  }

  setupHomeScreenPosts() async {
    setState(() {
      _loading = true;
    });
    List homeScreenPosts =
        await DatabaseMethods.getHomeScreenPosts(widget.currentUserId);
    if (mounted) {
      setState(() {
        _homeScreenPosts = homeScreenPosts;
        _loading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    setupHomeScreenPosts();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          IconButton(
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => SearchScreen(
                    currentUserId: widget.currentUserId,
                  ),
                ),
              );
            },
            icon: Icon(Icons.search),
          ),
        ],
        automaticallyImplyLeading: false,
        title: Text('Home'),
        centerTitle: true,
      ),
      body: RefreshIndicator(
        onRefresh: () => setupHomeScreenPosts(),
        child: ListView(
          physics: BouncingScrollPhysics(
            parent: AlwaysScrollableScrollPhysics(),
          ),
          children: [
            _loading ? LinearProgressIndicator() : SizedBox.shrink(),
            SizedBox(height: 5),
            Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                SizedBox(height: 5),
                Column(
                  children: _homeScreenPosts.isEmpty && _loading == false
                      ? [
                          SizedBox(height: 5),
                          Padding(
                            padding: EdgeInsets.symmetric(horizontal: 25),
                            child: Text(
                              'There is No New posts',
                              style: TextStyle(
                                fontSize: 20,
                              ),
                            ),
                          ),
                        ]
                      : showHomeScreenPosts(widget.currentUserId),
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
}

2

Answers


  1. Chosen as BEST ANSWER

    Okay so I figured it out myself, all I had to do was call the collectionGroup 'userPosts' like so

    static Future<List<Post>> getHomeScreenPosts(String currentUserId) async {
        QuerySnapshot homePostsSnap = await FirebaseFirestore.instance
            .collectionGroup('userPosts')
            .orderBy('timestamp', descending: true)
            .get();
        List<Post> homeScreenPosts =
            homePostsSnap.docs.map((doc) => Post.fromDoc(doc)).toList();
    
        return homeScreenPosts;
      }
    

  2. Firebase does not have the a concept of "tables" the way relational/sql databases do. I.e. there is not a built-in method to access all documents labelled as a "post".

    Because of this, you’ll need to access each post through each of the user documents.

    Assuming you have a List of all of your user Id’s called allUserIds, then you can do something like the following:

    List<Post> allPostsForAllUsers = [];
    allUserIds.forEach((id) {
        allPostsForAllUsers.addAll(await getUserPosts(id));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search