You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firestore集合为空时如何显示指定Widget?

问题:Cloud Firestore集合为空时无法显示"No Data"文本

我的Cloud Firestore中集合A目前为空,后续会填充数据,希望集合无数据时显示Text("No Data")组件。以下是我的代码:

class Green extends StatefulWidget {
  const Green({Key? key}) : super(key: key);

  @override
  State<Green> createState() => _GreenState();
}

class _GreenState extends State<Green> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
      stream: FirebaseFirestore.instance
          .collection(uid)
          .where("gatename", isEqualTo: "A")
          .snapshots(),
      builder: (_, snapshot2) {
        if (snapshot2.hasError) return Text('Error = ${snapshot2.error}');

        if (snapshot2.hasData) {
          final ds = snapshot2.data!.docs;
          return Padding(
            padding: const EdgeInsets.all(38.0),
            child: Container(
              height: 600,
              child: ListView.builder(
                itemCount: ds.length,
                itemBuilder: (_, i) {
                  final d = ds[i].data();
                  return ListTile(
                    title: Text(d["time"].toString()),
                    leading: Text(d["gatename"].toString()),
                  );
                },
              ),
            ),
          );
        }
        return const Center(child: CircularProgressIndicator());
      },
    ));
  }
}

我尝试使用else if (snapshot.data!.docs.isEmpty){},但页面仍显示白屏,请问该如何解决?


解决方案

问题出在你判断集合为空的逻辑位置错误:当snapshot2.hasData为true时,即使集合里没有文档(ds.isEmpty),代码依然会执行ListView.builder,而itemCount为0的ListView会呈现白屏,不会触发你写的空判断分支。

你需要在snapshot2.hasData的分支内部,先检查文档列表是否为空,再决定渲染空状态文本还是列表:

修改后的代码如下:

class Green extends StatefulWidget {
  const Green({Key? key}) : super(key: key);

  @override
  State<Green> createState() => _GreenState();
}

class _GreenState extends State<Green> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
      stream: FirebaseFirestore.instance
          .collection(uid)
          .where("gatename", isEqualTo: "A")
          .snapshots(),
      builder: (_, snapshot2) {
        if (snapshot2.hasError) return Text('Error = ${snapshot2.error}');

        // 加载中状态
        if (snapshot2.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }

        if (snapshot2.hasData) {
          final ds = snapshot2.data!.docs;
          // 检查文档列表是否为空
          if (ds.isEmpty) {
            return const Center(child: Text("No Data"));
          }
          // 有数据时渲染列表
          return Padding(
            padding: const EdgeInsets.all(38.0),
            child: Container(
              height: 600,
              child: ListView.builder(
                itemCount: ds.length,
                itemBuilder: (_, i) {
                  final d = ds[i].data();
                  return ListTile(
                    title: Text(d["time"].toString()),
                    leading: Text(d["gatename"].toString()),
                  );
                },
              ),
            ),
          );
        }
        // 兜底的空状态(理论上不会走到这里)
        return const Center(child: Text("No Data"));
      },
    ));
  }
}

关键修改点:

  • 将加载状态的判断改为检查connectionState == ConnectionState.waiting,更准确对应数据加载中的阶段
  • 在hasData分支内,先判断ds.isEmpty,为空则返回Text("No Data")
  • 保留了兜底的空状态返回,避免极端情况出现白屏

内容的提问来源于stack exchange,提问作者AsiF SHaik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 18:01:25