Turn a list of models into a feed (flutter)

Viewed 97

I have a function that gets all the posts in my database:

    fetchPosts() async {

      final userRef = FirebaseFirestore.instance.collection('users');

      final QuerySnapshot result = await userRef.get();

      List<Post> listPosts = [];

      result.docs.forEach((res) async {
        print(res.id);
        QuerySnapshot posts = await userRef.doc(res.id).collection("posts").get();

        posts.docs.forEach((res) {
          listPosts.add(Post.fromJson(res.data() as Map<String, dynamic>));
        });

        print(listPosts);
      });
    }

I call this from the home page where the feed of posts needs to be. Right now when it gets the list of post models, it prints like this:

flutter: [Post: {id: glowing_150_1634298846.220598, caption: hey!, postUrlString: https://firebasestorage.googleapis.com:443/v0/b/globe-e8b7f.appspot.com/o/glowing%2Fposts%2Fglowing_150_1634298846.220598.png?alt=media&token=131c1c88-278a-4cab-b4a2-948a0bceb8bf, postedDate: Timestamp(seconds=1640751651, nanoseconds=282563000)}, Post: {id: esmeamy_825_1635550477.162272, caption: <3, postUrlString: https://firebasestorage.googleapis.com:443/v0/b/globe-e8b7f.appspot.com/o/esmeamy%2Fposts%2Fesmeamy_825_1635550477.162272.png?alt=media&token=251c6592-a272-4bce-bbf5-e4b1f3fa2fbe, postedDate: Timestamp(seconds=1640751651, nanoseconds=291939000)}, Post: {id: erika_121_1629981490.158204, caption: no <3, postUrlString: https://firebasestorage.googleapis.com:443/v0/b/globe-e8b7f.appspot.com/o/erika%2Fposts%2Ferika_121_1629981490.158204.png?alt=media&token=d2202c86-1476-407b-b817-28dee3891782, postedDate: Timestamp(seconds=1640751651, nanoseconds=295732000)}, Post: {id: erika_214_1629981403.6358252, caption:<…>

Here is what the homeScreen code is like:

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:globe_flutter/services/database.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  static const String id = "home_screen";

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

class _HomeScreenState extends State<HomeScreen> {
  // List allposts = [(post: Post, owner: String)];

  Widget _buildPost(
      String username, String imageUrl, String likeCount, String caption) {
    return Container(
      color: Colors.white,
      child: Column(
        children: [
          Container(
            height: 50,
            color: Colors.deepOrangeAccent[100],
            child: Row(
              children: [
                SizedBox(width: 5),
                CircleAvatar(),
                SizedBox(width: 5),
                Text(username, style: TextStyle(fontSize: 15)),
                SizedBox(width: 250),
                Icon(Icons.more_horiz)
              ],
            ),
          ),
          Stack(
            children: [
              Image.asset("images/post_background.jpg"),
              Padding(
                padding: const EdgeInsets.all(20.0),
                child: ClipRRect(
                    borderRadius: BorderRadius.circular(8.0),
                    child: Image.network(imageUrl, fit: BoxFit.cover)),
              ),
            ],
          ),
          Container(
            height: 100,
            child: Column(
              children: [
                const SizedBox(height: 5),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: const [
                    Icon(Icons.thumb_up_alt_outlined, size: 30),
                    Text("l", style: TextStyle(fontSize: 30)),
                    Icon(Icons.ios_share, size: 30)
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Text(likeCount + "likes", style: const TextStyle(fontSize: 20))
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [Text(caption, style: const TextStyle(fontSize: 15))],
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
          child: Column(
        children: [
          DatabaseManager().fetchPosts(),
          _buildPost(
              "cjmofficial",
              "https://firebasestorage.googleapis.com/v0/b/globe-e8b7f.appspot.com/o/cjmofficial%2Fposts%2Fcjmofficial_410_1635649266.639148.png?alt=media&token=881bc085-a4d8-4599-949b-c3754a52abdc",
              "100",
              "Love it here"),
          _buildPost(
              "arianagrande",
              "https://firebasestorage.googleapis.com/v0/b/globe-e8b7f.appspot.com/o/arianagrande%2Fprofile_picture.png?alt=media&token=d22ee20b-eb79-44a9-af4e-3794c8f5467c",
              "100",
              "Love it here"),
          _buildPost(
              "cjmofficial",
              "https://firebasestorage.googleapis.com/v0/b/globe-e8b7f.appspot.com/o/cjmofficial%2Fposts%2Fcjmofficial_410_1635649266.639148.png?alt=media&token=881bc085-a4d8-4599-949b-c3754a52abdc",
              "100",
              "Love it here"),
          _buildPost(
              "arianagrande",
              "https://firebasestorage.googleapis.com/v0/b/globe-e8b7f.appspot.com/o/arianagrande%2Fprofile_picture.png?alt=media&token=d22ee20b-eb79-44a9-af4e-3794c8f5467c",
              "100",
              "Love it here"),
          _buildPost(
              "cjmofficial",
              "https://firebasestorage.googleapis.com/v0/b/globe-e8b7f.appspot.com/o/cjmofficial%2Fposts%2Fcjmofficial_410_1635649266.639148.png?alt=media&token=881bc085-a4d8-4599-949b-c3754a52abdc",
              "100",
              "Love it here"),
          _buildPost(
              "arianagrande",
              "https://firebasestorage.googleapis.com/v0/b/globe-e8b7f.appspot.com/o/arianagrande%2Fprofile_picture.png?alt=media&token=d22ee20b-eb79-44a9-af4e-3794c8f5467c",
              "100",
              "Love it here"),
        ],
      )),
    );
  }
}

Instead of manually using the _buildPost function, how can I take the data of listPosts and create as many _buildPost functions as there are posts in the list AND make each of the posts in the feed take the data from the corresponding post model in the listPosts?

1 Answers

To display a list’s data in flutter, you can use ListView.builder() In your case, that would look like this:

ListView.builder(
    itemCount: listPosts.length,
    itemBuilder: (BuildContext context, int index) {
      // We retrieve the post at index « index »
      final post = listPosts[index]
      // Replace with your actual implementation of _buildPost
      return _buildPost(post.title, post.url)
    }
)
Related