0

I want my App to remember the status of the 'Like Button' after closing/re-opening it. I am using firebase db and flutter.

6
  • Where are you storing the like button status? Jun 7, 2019 at 22:38
  • I am going to use Shared Preferences but I do not know whether it is suitable or not.
    – Hasini
    Jun 7, 2019 at 22:51
  • @Hasini It depends on what the 'like button' is for? Is it a key part of the app? If so, I would say Shared Preferences is acceptable for something like that. Otherwise, you should consider how you're storing / going to store other data.
    – SamJakob
    Jun 7, 2019 at 23:06
  • @Hasini SharedPreferences are stored locally. This means that when the user uninstalls the app or clears data for it, all SharedPreferences will be lost. So it depends on what you want. If the user is interacting with other people you should consider using a cloud db or maybe even an online JSON file. Otherwise you could just use SharedPreferences or Local Storage. Please edit your question explaining what type of app you're making or what you're trying to accomplish.
    – Noodles
    Jun 7, 2019 at 23:34
  • @AlexLushiku I am developing a simple post publishing app.
    – Hasini
    Jun 8, 2019 at 9:15

3 Answers 3

7

I am assuming you are using Cloud Firestore, then you may need to structure your data properly on the database but I will give you an example to get things going.

Lets assume that the structure of documents on Firestore is similar to "posts"/postId where "posts" is the collection and postId represents a generic document inside the posts collection where each post has a like button.

Now, we can structure the user document on Firestore as follows:

uid: //(here goes the postId, you should also name the document by the same postId)
likedBy: //(This is an array of userId's, where if the user likes this post his Id will be placed here)

Note that you need to authenticate users and obtain their Id's, if this is not a feature in your app then perhaps you need to use Shared Preferences as someone has stated.

Then, in flutter, you need to check if the post is liked by the user. I will not tell you how to structure your application's architecture but to get whether the post that has the 'like' button is liked by the user or not can be done using the following asynchronous Dart code:

bool isPostLiked;
Future<DocumentSnapshot> docSnapshot = Firestore.instance.collection('posts').document(postId).get();
DocumentSnapshot doc = await docSnapshot;
if (doc['likedBy'].contains(userId)) {
    isPostLiked = true;
} else {
   isPostLiked = false;
}
4
  • 1
    This is no good! What if he has like 10k likes, maybe his app gets bigger. Is he going to do this on 10k people? What if he has on 1 page 5 posts, array of 50k strings? This would definetly overflow. He needs to use cloud functions to make a field which keeps track on the length of the field on the server. Then do a query to see if the user liked the post or not. Jan 11, 2021 at 15:30
  • @AlexandruStroescu The size of a Firestore document ID is 29 bytes (calculated as the number of UTF-8 encoded bytes + 1 per the documentation) so if you do actually get the 50k strings you would be getting less than 1.5MB in string arrays, so overflowing is not the case here. Nevertheless, you are correct that this approach is not scalable. A more scalable approach would be to create a likedBy sub-collection under posts and populate it with userId's, but this will be much more expensive as scalability costs more. However, the question asked did not warrant the burden of structuring FS.
    – Ali Amin
    Jan 14, 2021 at 8:52
  • Another solution could be , having liked post id in users document, we can check if the post id is present in the array and change the ui, that would cost less , but over the time the array gets larger , but not as fast as keeping the array in post document. Jun 22, 2022 at 17:24
  • @AliAmin You do know that there is also a size limit of 1MB on the doc size. Aug 10, 2022 at 2:01
4

Thank you Ali Amin Sir. I followed his guidelines. I used this code to update 'likedby' field.

Firestore.instance.runTransaction((transaction) async {
        DocumentSnapshot freshSnap = await transaction.get(document.reference);
        await transaction.update(freshSnap.reference, {
          'vote': freshSnap['vote'] + 1,
        });
        List<String> users = ["4"]; //userId
        await transaction.update(freshSnap.reference, {
          'likedby': FieldValue.arrayUnion(users),
        });
      });
1
  • This would work, but this has some security problems. He needs some strong security rules. Jan 11, 2021 at 15:32
4

This is not related to Firestore. But if anyone came here to know how to do this with SQL, MySQL database, please see the example below. I will explain this to newbies to Flutter.

The variable : this guy will manage all the things.`

bool _isLiked = false;

Widget initState : Here you should check the state with your backend. If the user already likes it, you can show that he already liked it.

@override
  void initState() {
    super.initState();

    if(widget.replyData.isLiked == 1){
      setState(() {
        _isLiked = true;
      });
    }
  }

Like Button :

    Theme(
       data: ThemeData(splashColor: Colors.red[200]),
       child: Material(
          elevation: 0,
          shape: CircleBorder(),
          clipBehavior: Clip.hardEdge,
          color: Colors.transparent,
          child: InkWell(
             child: Padding(
                padding: const EdgeInsets.all(10),
                child: Icon(
                   Icons.favorite,
                   color: _isLiked ? Colors.red : Colors.black12,
                   size: 20,
                 ),
              ),
              onTap: () {
                 if(_isLiked){
                    setState(() {
                       _isLiked = false;
 //Here you need to update the backend status(if user dislike). This depends on your architecture.
                       _replyRateManager(widget.replyData.replyId,_currentUser,"DELETE_REPLY_RATE");
                       _rateCount -= 1;
                    });
                 }else{
                     setState(() {
                        _isLiked = true;
 //Here you need to update the backend status(if user like). This depends on your architecture.
                        _replyRateManager(widget.replyData.replyId,_currentUser,"ADD_REPLY_RATE");
                        _rateCount += 1;
                     });
                 }
              },
           ),
        ),
    )

Final Result :

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.