'how can I save the state of the 'liked' post by the user?

I have two collections in firestore, 'users' and 'posts'. HomePage is where all the posts are displayed in a listview and every post has a 'like' button. I'm saving the liked posts in a set final _likedPosts = Set<Posts>(); on the page but it only temporarily saves the liked posts and it loses all that data once the app is closed. How can I save the user's _likedPosts permanently so that the data is retained. What query should I make for the users to retain the _likedPosts? or is there any other way for this?

This is how the Icon and onTap is currently,

final _likedPosts = _savedPosts.contains(post);

Icon(_likedPosts ? Icons.favorite : Icons.favorite_border,
            color: _likedPosts ? Colors.red : null),
        onTap: () {
          setState(() {
            if (_likedPosts) {
              _savedPosts.remove(post);
            } else {
              _savedPosts.add(post);
            }
          });
        }


Solution 1:[1]

Are you saving a liked post of a certain user? then I suggest getting that post(ID) and save it to an array in the users doc Liked-Posts per user. Because state doesn't persist or can't be saved unless you use an external db.

Solution 2:[2]

you have to create this item like class StatefulWidget

class MyLikeButton extends StatefulWidget { \\...

and after add to state class of this item add "with AutomaticKeepAliveClientMixin" like this:


class _MyLikeButtonState extends State<MyLikeButton> with AutomaticKeepAliveClientMixin {

  @override
  bool get wantKeepAlive => true; \\....

this will keep alive the changes in the item when scrolling, its that u want?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dean Villamia
Solution 2 Rodrigo Costa