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

Firebase中ListView.builder始终显示loading问题求助

问题分析与修复

你的代码一直显示loading,核心问题有两个:

  1. 没有返回ListView组件:在ConnectionState.done的分支里,你创建了ListView.builder但没有用return返回它,所以不管逻辑执行到哪,函数最后都会走到末尾的return Text("loading")。

  2. 多余的异步操作:data['friends']是Firestore文档里直接存储的数组,不需要用await获取,你写的waitList函数完全没用,还会造成变量赋值的混乱。


修复后的代码

Widget showFriend() {
  CollectionReference users = FirebaseFirestore.instance.collection('todos');
  return FutureBuilder<DocumentSnapshot>(
    future: users.doc(documentId).get(),
    builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
      if (snapshot.hasError) {
        return const Text("Something went wrong");
      }

      if (snapshot.hasData && !snapshot.data!.exists) {
        return const Text("Document does not exist");
      }

      if (snapshot.connectionState == ConnectionState.done) {
        Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
        // 直接从data里取出friends数组,不需要异步操作
        List<dynamic> fren = List.from(data['friends'] ?? []); // 加空值判断避免崩溃
        print(fren);
        
        if (fren.isNotEmpty) {
          // 这里一定要return ListView
          return ListView.builder(
            itemCount: fren.length,
            itemBuilder: (context, index) {
              return ListTile(title: Text('${fren[index]}'));
            },
          );
        } else {
          // 处理friends为空的情况,返回提示
          return const Text("暂无好友");
        }
      }

      // 只有当连接未完成时才显示loading
      return const Text("loading");
    },
  );
}

额外优化点

  • 给data['friends']加了?? []的空值判断,避免文档里没有friends字段时出现空指针异常。
  • 用fren.isNotEmpty替代fren.length > 0,更符合Dart的代码规范。
  • 给静态Text组件加了const,提升性能。

内容的提问来源于stack exchange,提问作者honj - t

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 05:55:30