检查 Firebase 中是否存在文档并根据图标返回 [英] Check if documents exists in Firebase and return according icon

查看:24
本文介绍了检查 Firebase 中是否存在文档并根据图标返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查 Firebase 集合中是否存在特定文档.据此,我的应用程序应显示彩色图标或灰色图标.我正在尝试用一个返回布尔值的方法来解决这个问题.在我的 Build Widget 中,我调用该方法并分配正确的图标.

I want to check if a specific document exists in a Firebase collection. According to that, my app should display a colored icon or a grey one. I'm trying to tackle the problem with a method, which returns a boolean. In my Build Widget, I call that method and assign the right icon.

这是我检查文档是否存在的方法:

Here is my method which checks if the document exists:

checkIfLikedOrNot(reference) async{
   DocumentSnapshot ds = await reference.collection("likes").document(currentUser.uid).get();
   print(ds.exists);
   return ds.exists;
}

打印在控制台中显示了正确的值,但我的构建小部件似乎忽略了一个事实,即布尔值是 true 并且总是返回应该在集合中没有文档时显示的图标.

The print shows the right values in the console, but my build widget seems to ignore the fact, that the boolean is true and always returns the icon which should be displayed if there is no document in the collection.

这是我的构建小部件的一部分:

Here is the part of my Build Widget:

 GestureDetector(
      child: checkIfLikedOrNot(list[index].reference) == true

      ? 
         Icon(
          Icons.favorite,
          color: Colors.red,
         )
      : 
         Icon(
         FontAwesomeIcons.heart,
         color: null,
         ),
 )

这句话的问题在哪里?有什么想法吗?

Where is the problem with this statement? Any ideas?

推荐答案

根据您的用例,您可以使用 FutureBuilder,或者你保持简单,创​​建一个变量来处理逻辑:

Depending on your usecase you can either use a FutureBuilder, or you keep it simple and create a variable to deal with the logic:

在您的小部件内部:

bool isLiked = false;

从 initState() 中调用您的函数:

Call your function from within initState():

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

改变你的逻辑来修改你的变量并告诉 Flutter 重新渲染:

Change your logic to modify your variable and tell Flutter to rerender:

    checkIfLikedOrNot() async{
       DocumentSnapshot ds = await reference.collection("likes").document(currentUser.uid).get();
        this.setState(() {
          isLiked = ds.exists;
        });

    }

画出对应的Icon:

Icon(isLiked?Icons.favorite:FontAwesomeIcons.heart,
     color: isLiked?Colors.red:null)

由于您显然正在处理值列表,因此将它们封装在 Object 中或使用 FutureBuilder 是有意义的.

Since you are apparently dealing with a list of values, it makes sense to encapsulate them in an Object or use the FutureBuilder.

这篇关于检查 Firebase 中是否存在文档并根据图标返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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