Home > Mobile >  Flutter: How to like and unlike a post using like button package
Flutter: How to like and unlike a post using like button package

Time:12-12

I am working on a project where I want to like and unlike an image. I wanted it a little fancy, so I used the package [like_button]https://pub.dev/packages/like_button). I watched an online tutorial for this, and for them, it worked for me it didn't work. Also, I want to update the number of like in the firebase. In the documentation, it asks us to use onTap() which I did but unfortunately, it's not working. Kindly help me with the solution. NOTE: I am not getting any error it's just that I like an image but after hot reload it doesn't update.

import 'package:flutter/material.dart';
import 'package:like_button/like_button.dart';

class LikeAnimation extends StatelessWidget {
  int likeCount = 0;
  bool isLiked = false;

  @override
  Widget build(BuildContext context) {
    return  LikeButton(
      isLiked: isLiked,
      likeCount: likeCount,
      circleColor:
    CircleColor(start: Colors.deepPurple, end: Colors.deepPurple.shade300),
      bubblesColor: BubblesColor(
        dotPrimaryColor: Colors.deepPurple.shade500,
        dotSecondaryColor: Colors.deepPurple.shade200,
      ),
      // likeCount: likeCount,
      countPostion: CountPostion.bottom,
      likeCountPadding: const EdgeInsets.only(top: 20, left: 18),
      countBuilder: (count, isLiked, text){
        final color = Colors.deepPurpleAccent[200];
        return Text(
          '$text likes',
          style: TextStyle(
            color: color,
            fontFamily: 'Sen',
            fontWeight: FontWeight.bold,
          ),
        );
      },
      likeBuilder: (isLiked) {
        return Padding(
          padding: const EdgeInsets.only(top: 20),
          child: Icon(
            Icons.favorite,
            size: 26,
            color: isLiked ? Colors.deepPurpleAccent : Colors.grey,
          ),
        );
      },
      onTap: (isLiked) async {
        this.isLiked = isLiked;
        likeCount  = this.isLiked ? 1 : -1;
        return !isLiked;
      },
    );
  }
}

```
`

Here the code is being called...

    Row(
                    children: [
                      LikeAnimation(),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 6),
                        child: Image.asset('Icons/comment.png', color: Colors.deepPurpleAccent[100],width: 20,),
                      ),
                    ],
                  ),

CodePudding user response:

use this in OnTap

    // Use setState to update the state of the widget

        setState(() {
      this.isLiked = isLiked;
      likeCount  = this.isLiked ? 1 : -1;
    });

CodePudding user response:

You have to store userID whoever user liked the image and then you have check wether the logged-in user liked it or not. So, based upon userID(s) you can make like button to true or false.

CodePudding user response:

First of all, I don't think the like button stores the number of likes. If you close the page and open it, you will still have the same effect as hot reload.

However this is my suggestion on how to do this:

class LikeAnimation extends StatefulWidget {
  const LikeAnimation({ super.key });

  @override
  State<LikeAnimation> createState() => _LikeAnimationState();
}

class _LikeAnimationState extends State<LikeAnimation> {
  int likeCount = 0;
  bool isLiked = false;
  var likeDB = FirebaseFirestore.instance.collection("Likes");
  String? uid;

  @override
  void initState(){
  super.initState();
  uid = FirebaseAuth.instance.currentUser.uid;
  //Assuming I have a collection I would do like this
  likeDB.doc("$uid_likes").get().then((snapshot){
 //If such document exist I know the user has liked the image or media file
 if(snapshot.hasData && snapshot.data != null){
    setState((){
      isLiked = true;
    });
 }
});
//I define a document called total likes in cloud firestore
likeDB.doc("total_likes").get().then((snapshot){
 //If such document exist I know the user has liked the image or media file
 if(snapshot.hasData && snapshot.data != null){
   setState((){
     likeCount = snapshot.data['count'];
   });
 }
});
}

  @override
  Widget build(BuildContext context) {
    return  LikeButton(
      isLiked: isLiked,
      likeCount: likeCount,
      circleColor:
    CircleColor(start: Colors.deepPurple, end: Colors.deepPurple.shade300),
      bubblesColor: BubblesColor(
        dotPrimaryColor: Colors.deepPurple.shade500,
        dotSecondaryColor: Colors.deepPurple.shade200,
      ),
      // likeCount: likeCount,
      countPostion: CountPostion.bottom,
      likeCountPadding: const EdgeInsets.only(top: 20, left: 18),
      countBuilder: (count, isLiked, text){
        final color = Colors.deepPurpleAccent[200];
        return Text(
          '$text likes',
          style: TextStyle(
            color: color,
            fontFamily: 'Sen',
            fontWeight: FontWeight.bold,
          ),
        );
      },
      likeBuilder: (isLiked) {
        return Padding(
          padding: const EdgeInsets.only(top: 20),
          child: Icon(
            Icons.favorite,
            size: 26,
            color: isLiked ? Colors.deepPurpleAccent : Colors.grey,
          ),
        );
      },
      onTap: (isLiked) async {
        this.isLiked = isLiked;
        likeCount  = this.isLiked ? 1 : -1;
        if(isLiked == true){
         await likeDB.doc('$uid_likes').set({'value': true});
         } else {
          await likeDB.doc('$uid_likes').delete();
         }
        return !isLiked;
      },
    );
  }
}

Then for total_likes you should use Cloud Functions. OnCreate method should be used to increment ( 1) count in the database and OnDelete should be used decrement (-1) count in the database.

  • Related