简体   繁体   中英

snapshot.data.docs.length not working on flutter

I make some listview and it have likes and comments section. I want to show how many likes and comments that post had. The like section works by displaying the number of users who like it, i try to show it with snapshot.data.docs.length.toString() from firestore but when i try to show how many comments with same code as like section it not working and only get 0.

this is inside comments field这是在我的 firestore 里面,评论区

Padding(
    padding: const EdgeInsets.only(top: 8),
    child: Padding(
      padding: const EdgeInsets.only(left: 15),
      child: Row(
        mainAxisAlignment:
            MainAxisAlignment.spaceEvenly,
        children: [
          Container(
            width: 80.0,
            child: Row(
              mainAxisAlignment:
                  MainAxisAlignment.start,
              children: [
                GestureDetector(
                  onLongPress: () {
                    Provider.of<PostFunction>(context,
                            listen: false)
                        .showLikes(
                            context,
                            documentSnapshot
                                .data()['title']);
                  },
                  onTap: () {
                    print('Adding like...');
                    Provider.of<PostFunction>(context,
                            listen: false)
                        .addLike(
                            context,
                            documentSnapshot
                                .data()['title'],
                            Provider.of<AuthenticationService>(
                                    context,
                                    listen: false)
                                .getUserUid);
                  },
                  child: Icon(
                    FontAwesomeIcons.arrowAltCircleUp,
                    color: kGreyColor,
                    size: 18.0,
                  ),
                ),
                StreamBuilder<QuerySnapshot>(
                    stream: FirebaseFirestore.instance
                        .collection('posts')
                        .doc(documentSnapshot
                            .data()['title'])
                        .collection('likes')
                        .snapshots(),
                    builder: (context, snapshot) {
                      if (snapshot.connectionState ==
                          ConnectionState.waiting) {
                        return Center(
                            child:
                                CircularProgressIndicator());
                      } else {
                        return Padding(
                          padding:
                              const EdgeInsets.only(
                                  left: 8.0),
                          child: RichText(
                            text: TextSpan(
                                text: snapshot
                                    .data.docs.length
                                    .toString(),
                                style: GoogleFonts
                                    .openSans(
                                        color:
                                            kGreyColor,
                                        fontSize: 16.0),
                                children: <TextSpan>[
                                  TextSpan(
                                      text: ' votes',
                                      style: GoogleFonts
                                          .openSans(
                                        color:
                                            kGreyColor,
                                        fontSize: 16.0,
                                      )),
                                ]),
                          ),
                        );
                      }
                    })
              ],
            ),
          ),
          SizedBox(width: 20),
          Container(
            width: 150.0,
            child: Row(
              mainAxisAlignment:
                  MainAxisAlignment.start,
              children: [
                GestureDetector(
                  onTap: () {
                    Provider.of<PostFunction>(context,
                            listen: false)
                        .showComments(
                            context,
                            documentSnapshot,
                            documentSnapshot
                                .data()['title']);
                  },
                  child: Icon(
                    FontAwesomeIcons.solidComments,
                    color: kGreyColor,
                    size: 16.0,
                  ),
                ),
                StreamBuilder<QuerySnapshot>(
                    stream: FirebaseFirestore.instance
                        .collection(' posts')
                        .doc(documentSnapshot
                            .data()['title'])
                        .collection('comments')
                        .snapshots(),
                    builder: (context, snapshot) {
                      if (snapshot.connectionState ==
                          ConnectionState.waiting) {
                        return Center(
                            child:
                                CircularProgressIndicator());
                      } else {
                        return Padding(
                          padding:
                              const EdgeInsets.only(
                                  left: 8.0),
                          child: Text(
                            snapshot.data.docs.length
                                .toString(),
                            style: GoogleFonts.openSans(
                                color: kGreyColor,
                                fontSize: 16.0),
                          ),
                        );
                      }
                    }),
              ],
            ),
          ),
          Spacer(),
          Provider.of<AuthenticationService>(context,
                          listen: false)
                      .getUserUid ==
                  documentSnapshot.data()['useruid']
              ? IconButton(
                  icon: Icon(EvaIcons.moreVertical,
                      color: kGreyColor, size: 16),
                  onPressed: () {
                    Provider.of<PostFunction>(context,
                            listen: false)
                        .showPostOptions(
                            context,
                            documentSnapshot
                                .data()['title']);
                  })
              : Container(width: 0.0, height: 0.0)
        ],
      ),
    ),
  ),

Replace.collection(' posts')

with.collection('posts')

in the “comments” section of the Streambuilder.

Your stream data is coming as empty as the database cannot find a collection with name (“ posts”). So when you try to show how many comments the post had with the same code as the “likes” section it is not working and only getting 0 each time.

just declare the dataType of builder's arguments..i mean, builder:(BuildContext context,AsyncSnapshot snapShot). check the image

Could you please try this one?

StreamBuilder(
  stream: firestoreDB,
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (!snapshot.hasData) {
      return Center(child: CircularProgressIndicator());
    }
    return ListView.builder(
      itemCount: snapshot.data!.size,
      itemBuilder: (context, index) {
        return Card(
          child: ListTile(
            title: Text(snapshot.data!.docs[index]['name']),
            subtitle: Text(snapshot.data!.docs[index]['description']),
          ),
        );
      },
    );
  },
),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM