简体   繁体   English

从 FirebaseFirestore 查询数据不起作用

[英]Query data from FirebaseFirestore not working

I want to query the data in a collection in Firestore.我想查询 Firestore 集合中的数据。 This is the code I used in initState:这是我在 initState 中使用的代码:

  @override
  void initState() {
    super.initState();
    var nws;
    FirebaseFirestore.instance
      .collection('News')
      .get()
      .then((QuerySnapshot querySnapshot) {
        querySnapshot.docs.forEach((doc) {
        nws = doc["news"] // PRINT STATEMENT 1 
        print(nws);
        });
    });
    print(nws); // PRINT STATEMENT 2
  }

The issue I am facing is that PRINT STATEMENT 1 is correctly printing the data in Firestore but PRINT STATEMENT 1 is printing null .我面临的问题是PRINT STATEMENT 1正在 Firestore 中正确打印数据,但PRINT STATEMENT 1正在打印 null What is my mistake?我的错误是什么? I want to use nws in a Text Widget.我想在文本小部件中使用 nws。

var news;
void getFirebaseData() async {
await FirebaseFirestore.instance.collection("News").get().then((querySnapshot) {
  querySnapshot.docs.forEach((result) {
    setState(() {
      news = result.data();
    });
   });
  });
print("***2***" +  news['news'].toString());
}

Let me know if this works out, It's tested and working.让我知道这是否可行,它已经过测试并且可以正常工作。 You should handle null values I would suggest adding a null value checker like您应该处理 null 值我建议添加一个 null 值检查器,例如

if (result.data().isEmpty)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么将数据从一个 Activity 传输到另一个在 firebasefirestore 的查询中不起作用 - Why does transfering data from one Activity to another doesnt work inside a query in firebasefirestore RecyclerView 无法从 FirebaseFirestore 正确加载数据 - RecyclerView not loading data correctly from FirebaseFirestore FirebaseDatabase 和 FirebaseFirestore 数据处理和检索数据的问题 - Issue with FirebaseDatabase and FirebaseFirestore Data Manupulate and Retriving data 如何使用 Collections 从 FirebaseFirestore 检索 arrays? - How to retrieve arrays from FirebaseFirestore using Collections? 尝试使用 picasso 显示来自 FirebaseFirestore 的图像时出错 - Error while trying to display images from FirebaseFirestore using picasso FirebaseFirestore delete() function 当同时从 2 个客户端调用时会在两个客户端都成功 - FirebaseFirestore delete() function when called from 2 clients at the same time gives success in both clients 如果我将时间存储为ServerValue.TIMESTAMP,则如何从FirebaseFirestore中检索RecyclerView中的日期和时间 - How to retrieve date and time in a RecyclerView from FirebaseFirestore if i have stored time as ServerValue.TIMESTAMP in the database FirebaseFirestore 中的多个 whereEqualTo 条件 - Multiple whereEqualTo condition in FirebaseFirestore FirebaseFirestore多个进程 - FirebaseFirestore multiple processes 在 Intents 中传递 FirebaseFirestore 引用 - Pass FirebaseFirestore reference in Intents
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM