0

I'm using a future builder in a method and trying to switch to a Streambuilder but struggling a it with that heres my code may be anyone can help

class _MeineFreundeState extends State<MeineFreunde> {
  Icon custIcon = Icon(Icons.search);
  Widget cusSearchBar = Text("Meine Freunde");
  Stream myVideos;
  int likes = 0;
  int videos = 0;
  int followers;
  int following;
  bool dataisthere = false;
  @override
  void initState() {
    super.initState();
    getalldata();
  }

  getalldata() async {
    var listOfIds = [];
    String myID = FirebaseAuth.instance.currentUser.uid;
    var idofotheruser = await FirebaseFirestore.instance
        .collection('meinprofilsettings')
        .doc(myID)
        .collection('following')
        .get();
    following = idofotheruser.docs.length;
    idofotheruser.docs.forEach((element) {
      listOfIds.add(element.id);
    });
    print(listOfIds);

    myVideos = FirebaseFirestore.instance
        .collection('videos')
        .where('uid', isEqualTo: 'Fp3unLwcl2SGVh4MbUPiRVAylYV2')
        .snapshots();
    var documents = await FirebaseFirestore.instance
        .collection('videos')
        .where('uid', isEqualTo: 'Fp3unLwcl2SGVh4MbUPiRVAylYV2')
        .get();

    if (!mounted) return;
    setState(() {
      videos = documents.docs.length;
    });
    for (var item in documents.docs) {
      likes = item.data()['likes'].length + likes;
    }
    var followersdocuments = await FirebaseFirestore.instance
        .collection("meinprofilsettings")
        .doc(myID)
        .collection('followers')
        .get();
    var followingdocuments = await FirebaseFirestore.instance
        .collection("meinprofilsettings")
        .doc(myID)
        .collection('following')
        .get();
    followers = followersdocuments.docs.length;
    following = followingdocuments.docs.length;

    setState(() {
      dataisthere = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    return getBody(context);
  }

  Widget getBody(BuildContext context) {
    return dataisthere == false
        ? Scaffold(body: Center(child: CircularProgressIndicator()))
        : Stack(children: <Widget>[
            Scaffold(
              appBar: AppBar(
                actions: [
                  IconButton(
                    icon: Icon(Icons.search),
                    onPressed: () {
                      Navigator.of(context)
                          .pushNamed(Searchuserinmeinebeitraege.route);
                    },
                  ),
                ],
                backgroundColor: Colors.transparent,
                elevation: 0.0,
              ),
              body: RefreshIndicator(
                onRefresh: _handleRefresh,
                color: Colors.black,
                strokeWidth: 4,
                child: ListView(
                  children: [
                    Column(children: <Widget>[
                      SizedBox(
                        height: 5,
                      ),
                      StreamBuilder(
                          stream: myVideos,
                          builder: (context, snapshot) {
                            if (snapshot.connectionState ==
                                ConnectionState.waiting) {
                              return Center(child: CircularProgressIndicator());
                            }

                            if (videos > 0) {
                              return StaggeredGridView.countBuilder(
                                scrollDirection: Axis.vertical,
                                shrinkWrap: true,
                                physics: ScrollPhysics(),
                                crossAxisCount: 3,
                                itemCount: snapshot.data.docs.length,
                                itemBuilder: (context, index) {
                                  DocumentSnapshot video =
                                      snapshot.data.docs[index];
                                  return InkWell(
                                    onTap: () {
                                      NavigationService.instance
                                          .navigateToRoute(MaterialPageRoute(
                                              builder: (context) {
                                        return VideoPage(
                                          video.data()['videourl'],
                                          video.data()['uid'],
                                          video.id,
                                        );
                                      }));
                                    },
                                    child: Card(
                                      elevation: 0.0,
                                      child: ClipRRect(
                                        borderRadius: BorderRadius.circular(25),
                                        clipBehavior:
                                            Clip.antiAliasWithSaveLayer,
                                        child: Image.network(
                                          video.data()['previewimage'],
                                          fit: BoxFit.cover,
                                        ),
                                      ),

                                      //imageData: searchImages[index],
                                    ),
                                  );
                                },
                                staggeredTileBuilder: (index) =>
                                    StaggeredTile.count(
                                        (index % 7 == 0) ? 2 : 1,
                                        (index % 7 == 0) ? 2 : 1),
                                mainAxisSpacing: 8.0,
                                crossAxisSpacing: 4.0,
                              );
                            } else {
                              return Center(
                                child: Padding(
                                  padding:
                                      const EdgeInsets.fromLTRB(0, 100, 0, 0),
                                  child: Container(
                                    child: Text(
                                      "No Videos Yet",
                                      style: TextStyle(
                                          fontSize: 18, color: Colors.black),
                                    ),
                                  ),
                                ),
                              );
                            }
                          }),
                    ]),
                  ],
                ),
              ),
            ),
          ]);
  }

  Future _handleRefresh() async {
    await Future.delayed(new Duration(seconds: 2));
    setState(() {
      getalldata();
    });
    return null;
  }
}

I am a beginner with flutter, I know that I just can change FuturBuilder into Streambuilder and then future to stream but what about How I'm getting the data is there any difference I Mean something like this line

 video.data()['videourl'],

Is it equal or is there any difference and also how can I change it in getalldata method. If you need more information please leave a comment.

1 Answers1

1

StreamBuilder is different from FutureBuilder in many ways one main difference being

The main job of the FutureBuilder is to complete the future and return the result once the result is returned it has no way to fetch the latest snapshot from the future unless its parent rebuilds. Once the future attached returns the result the builder method gets executed to refresh the Ui.

while incase of StreamBuilder it contiuously listens to your specified collection and gets you the latest snapshot in realtime. that means any document in your firestore collection changes you get the latest updated collection and builder method rebuilds to refresh the UI.

You could use StreamBuilder to fetch data from your firestore's collection like this

 String myID = FirebaseAuth.instance.currentUser.uid;
   final  queryVideos = await FirebaseFirestore.instance
         .collection('videos')
        .where('uid', arrayContains: listOfIds)

StreamBuilder<DocumentSnapshot>(
        stream: queryVideos.snapshots(),
        builder:
            (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
        if (snapshot.data == null) {
             return Center(child: CircularProgressIndicator()); /// show a loader
        } else if (snapshot.data.docs.isEmpty) {
            return const SizedBox.shrink(); // show an empty widget no docs
       } else
           return StaggeredGridView.countBuilder(
                   scrollDirection: Axis.vertical,
                    shrinkWrap: true,
                     physics: ScrollPhysics(),
                     crossAxisCount: 3,
                     itemCount: snapshot.data.docs.length,
                     itemBuilder: (context, index) {
                     /// fetch a doc by Index
                     final doc = snapshot.data.docs[index];
                     return InkWell(
                              onTap: () {
                                NavigationService.instance
                                .navigateToRoute(MaterialPageRoute(
                                   builder: (context)=>VideoPage(
                                          doc['videourl'], // this is how you access each property in a document
                                          doc['uid'],
                                          doc['id']
                                         ));
                                },
                     child: YourWidget());
                   }));

    });

Mahesh Jamdade
  • 17,235
  • 8
  • 110
  • 131