我正在try 创建一个包含Firebase文档的列表流. 这是我目前的功能:

     Future<List<Service>> getServicesById(id) async {
    List<Service> services = [];
    for (String ids in id) {
      FirebaseFirestore.instance
          .collection('Services')
          .doc(ids)
          .get()
          .then((value) {
        services.add(Service.fromJson(value.data()!));
      });
    }
    return services;
   }

如何将其传输到流中,并返回服务列表?

推荐答案

如下所示更改您的方法:

Stream<Service> getServicesById(List<String> ids) async* {
  for (String id in ids) {
    final DocumentSnapshot document = await FirebaseFirestore.instance
        .collection('Services')
        .doc(id)
        .get();

    yield Service.fromJson(document.data()!);
  }
}

如果您想立即退货:

Stream<List<Service>> getServicesById(List<String> ids) async* {
  List<Service> services = [];

  for (String id in ids) {
    final DocumentSnapshot document = await FirebaseFirestore.instance
        .collection('Services')
        .doc(id)
        .get();

    if (document.exists) {
      services.add(Service.fromJson(document.data()!));
    }
  }

  // Yield the list of services when the loop is done
  yield services;
}

Flutter相关问答推荐

下拉图标未居中

Flutter -如何将导航轨道标签靠左对齐?

Flutter AppBar Animation反向调试

如何将 colored颜色 阴影作为默认容器 colored颜色 应用于自定义窗口小工具?

Ffltter:发布版本中的Path NotFoundException

从超级应用程序启动时,Flutter 小应用程序中未加载资源

无法在我的Flutter 应用程序中使用GoRouter测试导航

BoxConstraints强制使用无限宽度(列中的Listview)

如何在Flutter 中使用滚动展开窗口小部件

如何在flutter中将所有单词的第一个字母大写

Flutter http 请求获取 null

如何拥有 StreamProvider 的多个侦听器,其中稍后添加的侦听器接收最新数据?

在flutter中从图库或相机中 Select 图像的方法

当我使用 Confetti Widget 时,Flutter Android 和 IOS 应用程序崩溃

如何在 flutter 中同时使用 ButtonStyle() 和 ElevatedButton.styleFrom() ?

Future.wait() 中的 futures 可以顺序调用吗?

将一个 Flutter 应用程序集成到另一个 Flutter 应用程序中

根据索引/变量更改小部件的 colored颜色

如何从圆角go 除背景 colored颜色

如何从 MemoryFileSystem 字节创建假 dart:io 文件?