在 Flutter 中重新打开后记住 Like Button 的状态

Has*_*ini 0 firebase flutter

我希望我的应用程序在关闭/重新打开后记住“喜欢按钮”的状态。我正在使用 firebase db 和 flutter。

Ali*_*min 7

我假设您正在使用 Cloud Firestore,那么您可能需要在数据库上正确构建数据,但我会举一个例子来让事情顺利进行。

让我们假设文件在公司的FireStore结构相似,"posts"/postId这里"posts"是收集和postId代表的职位集合,其中每一个职位都有一个类似按钮内部的通用文件。

现在,我们可以按如下方式构建 Firestore 上的用户文档:

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)
Run Code Online (Sandbox Code Playgroud)

请注意,您需要对用户进行身份验证并获取他们的 ID,如果这不是您的应用程序中的一项功能,那么您可能需要像某人所说的那样使用共享首选项。

然后,在 flutter 中,您需要检查用户是否喜欢该帖子。我不会告诉您如何构建应用程序的架构,而是要了解用户是否喜欢带有“喜欢”按钮的帖子,可以使用以下异步 Dart 代码完成:

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)
Run Code Online (Sandbox Code Playgroud)