【问题标题】:StreamBuilder with Firestore loading vs no data具有 Firestore 加载与无数据的 StreamBuilder
【发布时间】:2020-05-19 15:15:33
【问题描述】:

这对我来说有点像一个错误,但我不确定。我在通过 Stream Builder 运行的 Flutter 应用程序中有简单的 Firestore 查询。看起来像这样 -

StreamBuilder(
  stream: Firestore.instance.collection('users').where('toNumber', isEqualTo: '123').snapshots();
  builder: (context, snapshot) {
  if (!snapshot.hasData) {
    return Center(
      child: CircularProgressIndicator(),
    );
  } else {
    if (snapshot.data.length == 0) {
      return Center(child: Text("No Data"));
    } else {
      return ListView.builder(
        itemCount: snapshot.data.length,
        itemBuilder: (context, index) =>
            _buildList(
                context, snapshot.data[index]),
      );
    }   
  }
)

问题在于,如果查询没有返回任何结果,那么您在连续进度指示器中看到的所有内容。我认为hasData 会返回 true,但似乎情况并非如此。我也尝试过使用 ConnectionState,但这总是返回 .waiting

在这种情况下,您如何区分正在加载的查询和不返回任何结果的查询?

【问题讨论】:

  • 分享查询将帮助我们帮助您。
  • 啊,是的,这会很有帮助!已更新。
  • 我知道您将查询放在流属性中只是为了举例,但您可能想单独显示它,否则其他用户会说这是问题的一部分,因为它会重新- 每次重建小部件时打开流。
  • 我明白你在说什么,但即使上面的内容被简化了,它仍然显示相同的症状。实际上,虽然它并没有太大的不同,因为我只是从一个集团返回相同的流。
  • @ChrisEdgington 嗨,您找到发生这种情况的原因了吗?我也有同样的情况。当没有数据时,connectionState 总是“等待”。一旦我将文档添加到 Firestore,connectionState 就会变为“活动”

标签: firebase flutter google-cloud-firestore


【解决方案1】:

尝试以下方法:

if (!snapshot.hasData) {
 if (snapshot.data.length == 0) {
      return Center(child: Text("No Data"));
    }
   else{ 
    return Center(
      child: CircularProgressIndicator(),
    );
  }
} 

【讨论】:

  • 有了这个我得到The getter 'length' was called on null.
  • 你可以试试 if(snapshot != null){if(snapshot.data.length == 0){.....
【解决方案2】:

这是我的构建方法。我刚刚测试了它,它正在工作。

@override
Widget build(BuildContext context) {
    return StreamBuilder(
        stream: firestore
            .collection('todos')
            .where('state', isEqualTo: false)
            .snapshots(),
        builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
          print(snapshot.connectionState);
          if (!snapshot.hasData) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
          return snapshot.data.documents.isNotEmpty
              ? ListView.builder(
                  itemCount: snapshot.data.documents.length,
                  itemBuilder: (_, index) {
                    return Text(snapshot.data.documents[index].data["title"]);
                  })
              : Text('No Data');
        });
}

打印出来:

I/flutter ( 6216): ConnectionState.waiting
I/flutter ( 6216): ConnectionState.active

【讨论】:

  • 感谢@easeccy,但这并不能解决“无数据”的情况。
  • 更新了答案。
猜你喜欢
  • 2021-03-03
  • 2019-04-20
  • 2021-02-20
  • 2020-05-28
  • 1970-01-01
  • 1970-01-01
  • 2021-07-26
  • 2022-11-17
  • 2018-08-11
相关资源
最近更新 更多