在Flutter中重新打开后,记住“赞"按钮的状态 [英] Remember the status of the Like Button after re-opening in Flutter

查看:119
本文介绍了在Flutter中重新打开后,记住“赞"按钮的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的应用在关闭/重新打开后能记住赞按钮"的状态.我正在使用Firebase db和flutter.

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

推荐答案

我假设您正在使用Cloud Firestore,那么您可能需要在数据库上正确构建数据结构,但我将举一个例子来说明问题.

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.

让我们假设Firestore上的文档结构类似于"posts"/postId,其中"posts"是集合,而postId代表posts集合内的通用文档,其中每个帖子都有一个like按钮.

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.

现在,我们可以按照以下步骤在Firestore上构建用户文档:

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)

请注意,您需要对用户进行身份验证并获取其ID,如果这不是您应用程序中的功能,那么也许您需要像别人所说的那样使用共享首选项".

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.

然后,您需要检查用户是否喜欢该帖子.我不会告诉您如何构建应用程序的体系结构,但是可以使用以下异步Dart代码来获取用户是否喜欢具有"like"按钮的帖子:

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

这篇关于在Flutter中重新打开后,记住“赞"按钮的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆