I'm trying to display the amount of comments every post has. Currently, the like count works so I tried to do something similar to what the likeCount function was doing. Once that didn't work, I went searching online everywhere to see if there were any other solutions, so far nothing has worked for me. This is what I have.
This is the function I think is having the problem. I tested adding a comment and it didn't write to Firebase.
getUserCommentCount() async {
bool commented = comments[currentOnlineUserId] == true;
if (commented) {
postsReference
.document(ownerId)
.collection("usersPosts")
.document(postId)
.updateData({"commented.$currentOnlineUserId": true});
setState(() {
//print(commentCount);
commentCount = commentCount + 1;
commented = true;
comments[currentOnlineUserId] = true;
});
}
}
int getTotalNumberOfLikes(likes) {
if (likes == null) {
return 0;
}
int counter = 0;
likes.values.forEach((eachValue) {
{
counter = counter + 1;
}
});
return counter;
}
int getTotalNumberOfComments(comments) {
if (comments == null) {
return 0;
}
int counter = 0;
comments.values.forEach((eachValue) {
{
counter = counter + 1;
}
});
return counter;
}
This is my function that adds and subtracts the likes. It works perfectly
controlUserLikePost() {
bool _liked = likes[currentOnlineUserId] == true;
if (_liked) {
postsReference
.document(ownerId)
.collection("usersPosts")
.document(postId)
.updateData({"likes.$currentOnlineUserId": false});
removeLike();
setState(() {
likeCount = likeCount - 1;
isLiked = false;
likes[currentOnlineUserId] = false;
});
} else if (!_liked) {
postsReference
.document(ownerId)
.collection("usersPosts")
.document(postId)
.updateData({"likes.$currentOnlineUserId": true});
addLike();
setState(() {
likeCount = likeCount + 1;
isLiked = true;
likes[currentOnlineUserId] = true;
showHeart = true;
});
Timer(Duration(milliseconds: 800), () {
setState(() {
showHeart = false;
});
});
}
}
And this is how the likeCount and commentCount are called. The likeCount works correctly. CommentCount just shows 0 comments
Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(left: 15.0),
child: Text(
"$likeCount likes",
style:
TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
),
),
],
),
Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(left: 15.0),
child: Text(
"$commentCount comments",
style:
TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
),
),
],
),
Any help would be much appreciated! Thanks