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

如何将Firestore数据存储到对象列表?添加数据后列表为空怎么解决

问题根因

  • 核心原因是异步执行顺序问题:FirebaseFirestore.instance.collection('data').get()属于异步网络请求,你通过then注册的回调函数,要等网络请求拿到返回数据后才会执行。但打印列表、return的代码是同步执行的,不会等待异步请求完成,执行打印逻辑时then里的列表填充操作还没运行,自然输出空列表。
  • 还有几个额外的代码错误:
    1. 重复调用了两次get()方法,发起了冗余的Firestore请求
    2. 类名不匹配:你定义的类是Artist,但声明列表、创建实例时用的是Artiste,拼写不一致
    3. 循环从i=1开始遍历,会直接跳过索引为0的第一个文档数据
    4. 方法返回值不符合预期:你声明方法是要拿艺术家列表,但实际返回的是原始的QuerySnapshot,没有返回组装好的业务对象列表

修正后的代码

首先修正类定义:

class Artist{
  final String id;
  final String name;
  final String year;
  Artist(this.id, this.name, this.year);
}

然后重构服务方法,用await等待异步操作完成再执行后续逻辑:

class ArtistsService{
  // 明确返回组装完成的Artist列表
  Future<List<Artist>> getAllArtists() async {
    List<Artist> localList = [];
    // await会等待异步请求结束,再执行后续代码
    final docSnapshot = await FirebaseFirestore.instance.collection('data').get();
    // 遍历所有文档,不要跳过第一条数据
    for (var doc in docSnapshot.docs) {
      String id = doc.id;
      String annee = doc["annee"].toString();
      String name = doc["artistes"].toString();
      print(id);
      print(annee);
      print(name);
      localList.add(Artist(id, name, annee));
    }
    // 此时列表已经填充完成,打印和返回都正常
    print("LIST : ${localList.toString()}");
    return localList;
  }
}

调用注意事项

调用getAllArtists方法时也需要用await等待异步结果返回,才能拿到完整的列表:

// 调用示例
List<Artist> artists = await ArtistsService().getAllArtists();

内容的提问来源于stack exchange,提问作者Alexis Leloup

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:24:04