toggleLike method
Implementation
Future<void> toggleLike(int postId) async {
final token = Hive.box('user_data').get('user_token');
if (token == null) {
Get.snackbar('Error', 'Please login to like posts');
return;
}
try {
final response = await _dioApiService.post(
endpoint: CommunityConstants.postLike(postId),
headers: {
'api-key': CommunityConstants.apiKey,
'Authorization': 'Bearer $token',
},
);
if (response.statusCode == 200) {
// Update the post in the local list
final posts = postsResponse.value?.data;
if (posts != null) {
final index = posts.indexWhere((p) => p.id == postId);
if (index != -1) {
final post = posts[index];
final updatedPost = Post(
id: post.id,
title: post.title,
content: post.content,
image: post.image,
isPinned: post.isPinned,
isApproved: post.isApproved,
likesCount: post.isLikedByUser
? post.likesCount - 1
: post.likesCount + 1,
commentsCount: post.commentsCount,
user: post.user,
community: post.community,
isLikedByUser: !post.isLikedByUser,
createdAt: post.createdAt,
updatedAt: post.updatedAt,
);
posts[index] = updatedPost;
postsResponse.value = PostsResponse(
data: posts,
links: postsResponse.value!.links,
meta: postsResponse.value!.meta,
);
}
}
}
} catch (e) {
Get.snackbar('Error', 'Failed to like post');
}
}