How to use StreamSubscription for posts?

Viewed 18

Hey there I'm trying to get my flutter app to display posts from the array in their group by using streamSubscription so that the app will refresh when a new post comes in. I know the function is wrong but this is the best I could come up with.

Below is my function

    Future<List<DocumentSnapshot>>getDocStream(groupID) async {

StreamSubscription<QuerySnapshot<Map<String, dynamic>>>? qn;
  List<DocumentSnapshot>? eventDocs;

    var firestore = FirebaseFirestore.instance;
    qn = firestore.collection('groups')
        .where('groupChatId', isEqualTo: groupID)
        .orderBy('date', descending: true)
        .snapshots().listen((event) {
      setState(() {
        eventDocs = event.docs;
      });
    });
     @override
  void dispose() {
    if (qn != null) qn.cancel();  
    super.dispose();
  }

  }

This is my FutureBuilder screen

 body: FutureBuilder(
  future: getDocStream(groupId),
  builder: (_, AsyncSnapshot<List<DocumentSnapshot>> snapshot){
    if(snapshot.hasData){
      return Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: ((_, index) {
                List<Widget> tiles = [];
                for (Map post in snapshot.data![index]['posts']) {
                tiles.add(
                  Expanded(
                    child: Container(
                      margin: EdgeInsets.all(2),
                      padding: EdgeInsets.all(1),
                      decoration: BoxDecoration(border:  Border.all(color:Colors.black)),
                      child: ListTile(
                        title: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(post['postText'], style: TextStyle(color: Colors.white),),
                            SizedBox(height: 5,),
                            Text(post['fromUser'], style: TextStyle(color: Colors.white),),
                            
                          ],
          
                        ),
                      ),
                    ),
                    
                  )
                );
              }
              return SizedBox(
                height: MediaQuery.of(context).size.height,
                child: ListView(
                  scrollDirection: Axis.vertical,
                  shrinkWrap: true,
                  physics: ScrollPhysics(),
                children: tiles
                ));
              }),
                
            ),
          ),
          isLoaded? Container(
            height: 50,
            child: AdWidget(ad: bannerAd),
            ): SizedBox()
        ],
      );
       
    }
    else{
      return Center(child: CircularProgressIndicator(),);
    }
  },
   ),

This is my firestore and the posts I'm trying to get as a stream. enter image description here

1 Answers

I have a low reputation to comment. Instead I am writing as an answer. As per the documentation the future must have been obtained earlier, e.g. during State.initState, State.didUpdateWidget, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder.

Related