I would like to add likes to the comments in my application that I wrote, but (The method 'contains' was called on null. Receiver: null Tried calling: contains("3hmly93fmrojxdlz09lh3dzmjqu2")) I'm getting this error. My codes are as follows what I need to do.
Future<void> LikeComment(String postId, String uid, List likes, String commentId) async {
try {
if (likes.contains(uid)) {
await _firestore.collection('posts').doc(postId).collection('comments').doc(commentId).update({
'likes': FieldValue.arrayRemove([uid]),
});
} else {
await _firestore.collection('posts').doc(postId).collection('comments').doc(commentId).update({
'likes': FieldValue.arrayUnion([uid]),
});
}
} catch (e) {
print(
e.toString(),
);
}
}
like
Row(
children: [
LikeAnimation(
isAnimating: widget.snap['likes'].contains(myUid),
smallLike: true,
child: IconButton(
onPressed: () async {
await FirestoreMethods().LikeComment(
myUid,
widget.snap['postId'],
widget.snap['commentId'],
widget.snap['likes'],
);
},
icon: widget.snap['likes'].contains(myUid)
? const Icon(
Icons.favorite,
color: Colors.red,
)
: const Icon(
Icons.favorite_border,
),
),
),
]),
CodePudding user response:
It is possible to get null from reading snap, try
widget.snap['likes']?? [],
and
isAnimating: widget.snap['likes']!=null && widget.snap['likes'].contains(myUid),
icon: widget.snap['likes']!=null && widget.snap['likes'].contains(myUid)
Also it is better to null check on others variable