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

查看:99
本文介绍了检查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?

推荐答案

根据您的用例,您可以使用

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(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天全站免登陆