0

I'm trying to get documents from Firebase but when I print the document it says 0. So that means there's no document, but it is actually. Here how I'm trying it

  Icon custIcon = Icon(Icons.search);
  Widget cusSearchBar = Text("Meine Freunde");
 Future myVideos;
  int likes = 0;
  int videos = 0;
  int followers;
  int following;
  bool dataisthere = false;

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

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

  getalldata() async {
    String myID = FirebaseAuth.instance.currentUser.uid;
    //get videos as future
    var uid = 'Fp3unLwcl2SGVh4MbUPiRVAylYV2';
   var  idofotheruser= await FirebaseFirestore.instance
        .collection('meinprofilsettings').doc(myID).collection('following').id.length;
    myVideos =  FirebaseFirestore.instance
       .collection('videos')
        .where('uid', isEqualTo:idofotheruser)
        .get();

    var documents = await FirebaseFirestore.instance
        .collection('videos')
        .where('uid', isEqualTo: idofotheruser).get();
        print(documents.docs.length);

        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;
    });
  }

  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,
                      ),
                      FutureBuilder(
                          future: 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

                              //picturesdontexists = true)
                              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),
                                    ),
                                  ),
                                ),
                              );
                          }),
                    ]),
                  ],
                ),
              ),
            ),
          ]);
  }

And here is my Firebase enter image description hereenter image description here

enter image description here

So what I'm trying to get all videos of the user that I follow. The uid in videos collection should be equal to the uid of a user that I follow user

Bawantha
  • 3,644
  • 4
  • 24
  • 36

1 Answers1

1

This problem is in this fragment of your code:

FirebaseFirestore.instance
        .collection('meinprofilsettings').doc(myID).collection('following').id

This is a very long-winded way to say 'following'. It does not read anything from the database, which is probably what you want to do.

Keep in mind that Firestore does not perform any type of server-side join when reading data. If you want to compare to a specific value in your query, you will have to provide that specific value in the code:

var uid = 'Fp3unLwcl2SGVh4MbUPiRVAylYV2';
FirebaseFirestore.instance
       .collection('videos')
       .where('uid', isEqualTo: uid)
       ...

So you'll need to determine the UID in a separate step, and then provide that value to the video query.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    I think this is going to turn out like the question you answered a few mins ago, where the video doc will need an array of ids of users who are following. https://stackoverflow.com/a/67149604/294949 – danh Apr 18 '21 at 14:30
  • I think you not understand I dont want only the document of one user I want all documents videos from that users that I follow . That what you doing is hardcoding one uid –  Apr 18 '21 at 15:27
  • The process is the same for multiple users. You'll need to create a list of the IDs for those users, and then load each of their docs separate - or in batches of up to 10 with `in`: https://firebase.google.com/docs/firestore/query-data/queries#in_not-in_and_array-contains-any – Frank van Puffelen Apr 18 '21 at 15:48
  • 1
    Agree about the pedagogy @FrankvanPuffelen. Agree about the votes, and I'll donate a few bucks to Bill Gates, also :-) (and I understand that's a poor analogy) – danh Apr 18 '21 at 16:00
  • Hmm do you have an example for your idea with the load each of their docs separate maybe a code because im not really understand how to do that ? –  Apr 18 '21 at 18:30
  • following is a collection an and the ids inside following are documents arent they? So can i not using the dochment as a list what you said ? Please give me an code example im really not unterstand what you mean –  Apr 18 '21 at 18:37
  • Here are some good reference questions of showing data from two collections: https://stackoverflow.com/questions/59061225/how-do-i-join-data-from-two-firestore-collections-in-flutter, https://stackoverflow.com/questions/54650261/firestore-replicating-a-sql-join-for-nosql-and-flutter, https://stackoverflow.com/questions/44185979/flutter-firebase-database-joining-two-nodes, https://stackoverflow.com/questions/52865578/how-to-inner-join-in-firestore – Frank van Puffelen Apr 18 '21 at 19:08
  • Please check my code so you can see what im trying and maybe explaining what I should do . So I have to wrap ,the howle widget with a streambuilder if I understand it correctly in this streambuilder I should get a list of all following datas and then ? How do I get access to all videos of the person that I following ????? –  Apr 19 '21 at 10:22