简体   繁体   中英

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);
            }
          });
        }

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM