How to Create like and dislike features in Flutter
Coding Flutter

How to Implement Like and Dislike Features in Flutter?

Spread the love

Here we will discuss how to implement the like and dislike features in Flutter for the Android and iOS apps. There can be many ways to implement the Like and Dislike features in Flutter but we will show the simplest possible way with neat code and easy to understand manner.

While building mobile apps many times we feel the requirement to implement features like marking something favorite or Like and Dislike features. For example, if you are building a shopping app then your app users may want to mark a couple of products as favorites so that they can access it later.

While explaining how to implement Like and Dislike Features in Flutter I will take the example of my joke app, Jokester. I have implemented the Like and Dislike feature in my app to suppress insipid and bad jokes so that only funny jokes surface to end users. Here is the screenshot for your reference.

We will keep our discussion limited to “How to implement Like and Dislike Features in Flutter” rather than the UI part. We will simply use material icons to implement UI as shown in the screenshot.

Here is the overall process along with steps for the Like and Dislike Buttons feature in a flutter.

Related Read: 20 Best App Review Sites to Submit Your App

Steps to Implement Like and Dislike Features in Flutter

1. Overall architecture

In order to implement the Like and Dislike Features in Flutter we will use the below overall structure –

In order to implement this functionality we will be using the shared_preferences package for local storage of like and dislike data and Firebase to upload the data to the server for consolidation. Our focus in this article would be the implementation of locally stored like and dislike features in Flutter.

In my project, I have a collection of jokes that are downloaded when someone opens the app. For simplicity, I will use three lists to store all the jokes collection, liked jokes collection, and disliked jokes collection.

Moving forward I will create UI (material Like and Dislike icon buttons), and create methods to push liked and disliked jokes to the respective collection and respective shared preference storage.

Let’s explore these steps in detail.

2. Add Package to the Project

This is a famous package to implement local storage of data in Flutter. You can install this plugin by running the below command in your project file directory –

flutter pub add shared_preferences

Once the package is added you need to import it into your project –

import 'package:shared_preferences/shared_preferences.dart';

This package is very simple to use. You can read the documentation here. For simplicity, I am providing the features of this package we are going to use to implement Like and Dislike features in the Flutter project.

Read data from local storage –

// Obtain shared preferences. final SharedPreferences prefs = await SharedPreferences.getInstance(); 

List<String> collectionofLikedJokesList = prefs.getStringList('likedJokes');

Write data to local storage –

// Obtain shared preferences.
final SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setStringList('likedJokes', collectionofLikedJokesList);

Important to note here is the unique id to read and write to local storage. For example, here we are using likedJokes as the id to write and read the collection of liked jokes Ids.

3. Create UI

While creating the like and Dislike buttons we will keep the icon dynamic and we will update them as per like or dislike actions. UI should transform something like this –

Like action -> Like Button highlighted -> Joke is added to Favorite jokes collection (shared preferences)

Since we are focusing only on Like and Dislike features in Flutter, we will be discussing UI elements related to only this particular area highlighted in the above screenshot.

likeAndDislikeButtons() {
      Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.only(
              left: 8,
              bottom: 8,
            ),
            child: InkWell(
                onTap: () {
                  //Method to push liked and disliked jokes 
                  saveLikeAndDislikeAction(true, jokeId);

                },
                child: Icon(
                  //highlight button if the joke is liked
                  liked == true ? Icons.thumb_up_alt : Icons.thumb_up_alt_outlined,
                  color: Colors.black54,
                )),
          ),
          Padding(
            padding: const EdgeInsets.only(
              left: 15,
              bottom: 8,
            ),
            child: InkWell(
                onTap: () {
                  //Method to push liked and disliked jokes 
                  saveLikeAndDislikeAction(false, jokeId);
                },
                child: Icon(
                  //highlight button if the joke is disliked
                  liked == false
                      ? Icons.thumb_down_alt
                      : Icons.thumb_down_alt_outlined,
                  color: Colors.black54,
                )),
          )
        ],
      );
  }

Now let’s talk about methods to push jokes to shared preferences, and pull jokes from shared preferences.

4. Create Methods to Fulfill Like and Dislike Features in Flutter

In order to implement the like and dislike features in our project we will use below three methods –

1. saveLikeAndDislikeAction(bool isLiked, String jokeId)

In this method, we will try to access the shared preference of liked and disliked jokes collection and add the joke Id to the respective bucket (liked bucket or disliked bucket).

To make this process more efficient and avoid the repeated addition of joke Ids we will check if the collection contains the given joke Id and if it is already there then we won’t repeat the addition to the list again. Here is the code –

Future<void> saveLikeAndDislikeAction(bool isLiked, String jokeId) async {
    final prefs = await SharedPreferences.getInstance();
    List<String> likedJokeIdCollection =
        prefs.getStringList('likedJokeIdCollection') ?? [];
    List<String> disLikedJokeIdCollection =
        prefs.getStringList('disLikedJokeIdCollection') ?? [];
    if (isLiked && likedJokeIdCollection.contains(jokeId) == false) {
      //joke has been liked and it is not repeaded like action
      likedJokeIdCollection.add(jokeId);
      prefs.setStringList('likedJokeIdCollection', likedJokeIdCollection);
      //Now let's remove this id from disliked jokes collection
      disLikedJokeIdCollection.remove(jokeId);
      prefs.setStringList('disLikedJokeIdCollection', disLikedJokeIdCollection);
    } else if (isLiked == false &&
        disLikedJokeIdCollection.contains(jokeId) == false) {
      //Joke has been disliked and it is not a repeated dislike action
      disLikedJokeIdCollection.add(jokeId);
      prefs.setStringList('disLikedJokeIdCollection', disLikedJokeIdCollection);
      //Now let's remove this jokeId from liked jokes collection
      likedJokeIdCollection.remove(jokeId);
      prefs.setStringList('likedJokeIdCollection', likedJokeIdCollection);
    }

    //This method will setSTate the value loked to true or false
    and render the like button as highlighted
    getTheJokeStatus(jokeId);

    //This method will refresh the jokes collection variable in our project
    refreshTheLikedDislikedAndNeutrealJokesCollection();
  }

2. getTheJokeStatus(String jokeId)

Using this method we will fetch the liked and disliked status of any joke by passing the joke Id. This method will set the state of the boolean variable, ‘liked’ of the current joke which will be used across the code for various purposes including highlighting the like or dislike button.

Here is the code –

Future<void> getTheJokeStatus(String jokeId) async {
    final prefs = await SharedPreferences.getInstance();
    List<String> likedJokeIdCollection =
        prefs.getStringList('likedJokeIdCollection') ?? [];
    List<String> disLikedJokeIdCollection =
        prefs.getStringList('disLikedJokeIdCollection') ?? [];
    if (likedJokeIdCollection.contains(jokeId)) {
      setState(() {
        liked = true;
      });
    } else if (disLikedJokeIdCollection.contains(jokeId)) {
      setState(() {
        liked = false;
      });
    }
  }

3. refreshTheLikedDislikedAndNeutrealJokesCollection()

Using this method we will fetch the liked and disliked jokes into local List type variables so that we can iterate it locally and show the favorite jokes collection. This method runs after every liked and dislike action to keep the favorite jokes collection updated.

Later you can create a page to iterate your favorite jokes. In my app, I have put a heart icon on the top right to show the collection of my favorite jokes. We won’t be talking about that because this article is limited to like and dislike features in Flutter.

Here is how I implemented this to keep the favorite jokes collection updated in my Jokester App. –

Future<void> getLikedAndDislikedJokesCollection() async {
    final prefs = await SharedPreferences.getInstance();
    List<String> likedJokeIdCollection =
        prefs.getStringList('likedJokeIdCollection') ?? [];
    List<String> uniqueLikedJokes = [];
    if (likedJokeIdCollection.isNotEmpty) {
      for (int i = 0; i < likedJokeIdCollection.length; i++) {
        var temp = likedJokeIdCollection[i].split('_');
        var tempJokeType = temp[0];
        int tempJokeId = int.parse(temp[1]);
        switch (tempJokeType) {
          case "dadJokesCollection":
            uniqueLikedJokes.add(
                "${dadJokesCollection[tempJokeId].stage}\n\n${dadJokesCollection[tempJokeId].punchline}");
            break;
          case "knockKnockJokesCollection":
            uniqueLikedJokes.add(
                "Knock, Knock.\nWho's there?\n${knockKnockJokesCollection[tempJokeId].punchline}");
            break;
          case "chuckNorrisJokesCollection":
            uniqueLikedJokes.add(chuckNorrisJokesCollection[tempJokeId].punchline);
            break;
          case "programmersJokesCollection":
            uniqueLikedJokes.add(programmersJokesCollection[tempJokeId].punchline);
            break;
          case "karenJokesCollection":
            uniqueLikedJokes.add(karenJokesCollection[tempJokeId].punchline);
            break;
        }
      }
    }

    setState(() {
      uniqueLikedJokesCollection = (uniqueLikedJokes.isEmpty)
          ? [
              "Looks like you haven't found 'the one' just yet.\nYour Favorite Jokes Collection is still waiting for its perfect match.\n\nLike any joke from any category by hitting 👍🏿 and we will add it here for you."
            ]
          : uniqueLikedJokes;
      uniqueDisLikedJokesCollection = uniqueDisLikedJokes;
    });
  }

This like and dislike feature is for local storage and you can add Firebase or any backend to push the liked and disliked jokes to the server to consolidate the likes and dislikes count like Facebook or any other social media.

Jokester-Horizontal-Promo

Final Thoughts

By implementing like and dislike features, you can gather valuable feedback and insights from your users. This information can help you understand user preferences, improve your content, and make data-driven decisions. Furthermore, incorporating social features like these can foster a sense of community and encourage users to engage with your application on a deeper level.

Overall, implementing like and dislike features in Flutter is an exciting opportunity to enhance user engagement, gather feedback, and improve your application’s user experience. By following the techniques discussed in this article, you can empower your users to express their opinions, create a more interactive environment, and build a stronger connection with your audience.

If you have any questions you can drop them in the comments below and I will try my best to explain and resolve your queries. Happy learning.

Related Reads:

Alok Rai
A passionate tech blogger who loves to read and write about technology, interesting concepts, and science. Additionally, I love to code and recently develop a mobile app, "The Mutual Fund Journal" for Indian users and working on it to extend for all.