Flutter – StreamBuilder

I’m working on a Flutter app and I’m encountering an issue with the StreamBuilder widget. I’m using StreamBuilder to display a list of posts, and I have a button to open the comment page for each post. When I switch from the home page to the comment page using Navigator.of(context).push(), the StreamBuilder on the home page rebuilds. As a result, when I return to the home page from the comment page, the list of posts is reset and I’m back to the first post.

I added a print statement to the StreamBuilder to see if it rebuilds, and it does while I’m on the comment page.

To make it easier to understand, I’ve created a video to illustrate the issue here.

I have already reviewed other questions related to this issue, but I have not found anything that has helped me.

Sure, here is the code for my entire StreamBuilder:

StreamBuilder(
  // StreamBuilder de refresh
  stream: Provider.of<MyProvider>(context, listen: false).refreshStream,
  builder: (context, snapshot) {
    print("rebuild");
    if (snapshot.hasData) {
      _uniqueKey = UniqueKey().toString();
    }
    return StreamBuilder(
      key: Key(_uniqueKey),
      stream: FirebaseFirestore.instance
          .collection("Users")
          .doc(FirebaseAuth.instance.currentUser!.uid)
          .snapshots(),
      builder: (context, snapshot) {
        if (snapshot.data == null) {
          // Chargement ...
          return const CupertinoActivityIndicator(
            radius: 25,
          );
        }

        if (snapshot.data!["followedPostsOnly"]) {
          // Afficher les posts des utilisateurs suivis uniquement
          if (snapshot.data!["followedAccounts"] == null ||
              snapshot.data!["followedAccounts"] == [] ||
              snapshot.data!["followedAccounts"].isEmpty) {
            // Aucun compte suivis = Aucun post à afficher
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    "Aucun compte suivi",
                    style: GoogleFonts.kanit(
                      fontSize: 30,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const Gap(30),
                  Padding(
                    padding: EdgeInsets.symmetric(
                        horizontal: MediaQuery.of(context).size.width * 0.05),
                    child: const Text(
                      "Pour afficher les posts de tous les utilisateurs de l'application, rendez-vous dans les réglages.",
                      textAlign: TextAlign.center,
                    ),
                  ),
                ],
              ),
            );
          }

          // Afficher les posts
          return StreamBuilder(
            stream: FirebaseFirestore.instance
                .collection("Posts")
                .where("author", whereIn: snapshot.data!["followedAccounts"])
                .orderBy("timestamp", descending: true)
                .snapshots(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                // Chargement ...
                return const CupertinoActivityIndicator(
                  radius: 25,
                );
              }
              if (snapshot.data == null || snapshot.data!.docs.isEmpty) {
                // Aucun post
                return Center(
                  child: Text(
                    "Aucun post",
                    style: GoogleFonts.kanit(
                      fontSize: 30,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                );
              }
              return Stack(
                children: [
                  // Message plus de posts (en dessous des tous les posts ce qui le rend visible seulement quand il n'y en a plus)
                  Center(
                    child: Text(
                      Provider.of<MyProvider>(context, listen: false)
                                  .foregroundPost ==
                              null
                          ? "Plus de posts ..."
                          : "",
                      style: GoogleFonts.kanit(
                        fontSize: 25,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),

                  // Posts
                  Stack(
                    children: List.generate(
                      snapshot.data!.docs.length,
                      (index) {
                        return MySimplePost(
                          postID: snapshot.data!.docs[index].reference.id,
                          stackIndex:
                              snapshot.data!.docs.length - 1 - index,
                        );
                      },
                    ),
                  ),
                ],
              );
            },
          );
        }
        // Afficher les posts de tout le monde
        return StreamBuilder(
          stream: FirebaseFirestore.instance
              .collection("Posts")
              .orderBy("timestamp", descending: false)
              .snapshots(),
          builder: (context, snapshot) {
            if (snapshot.data == null ||
                snapshot.data!.docs.isEmpty ||
                snapshot.data!.docs.isEmpty) {
              // Aucun post
              return Center(
                child: Text(
                  "Aucun post",
                  style: GoogleFonts.kanit(
                    fontSize: 30,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              );
            }
            WidgetsBinding.instance.addPostFrameCallback(
              (timeStamp) {
                Provider.of<MyProvider>(context, listen: false).setLastPost(
                  snapshot.data!.docs.first.reference.id,
                );
              },
            );
            return Stack(
              children: [
                // Message plus de posts (en dessous des tous les posts ce qui le rend visible seulement quand il n'y en a plus)
                Center(
                  child: Consumer<MyProvider>(
                    builder: (context, provider, _) {
                      return Text(
                        provider.foregroundPost == null
                            ? "Plus de posts ..."
                            : "",
                        style: GoogleFonts.kanit(
                          fontSize: 25,
                          fontWeight: FontWeight.bold,
                        ),
                      );
                    },
                  ),
                ),

                // Posts
                Stack(
                  children: List.generate(
                    snapshot.data!.docs.length,
                    (index) {
                      return MySimplePost(
                        postID: snapshot.data!.docs[index].reference.id,
                        stackIndex:
                            snapshot.data!.docs.length - 1 - index,
                      );
                    },
                  ),
                ),
              ],
            );
          },
        );
      },
    );
  },
)

NOTE: Please avoid looking at the details in the comment page. I am aware that there is an issue while posting a comment, but I will fix it later.

If anyone needs more details about my code, use-case, or anything else, please post a comment and I’ll respond quickly. I welcome any advice as I’m a beginner in development and looking to improve. Feel free to comment on anything in my code, even if it’s not related to my current issue.

Thanks.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật