dart 从未来列表到流列表Flutter Firebase

nkhmeac6  于 2023-09-28  发布在  Flutter
关注(0)|答案(1)|浏览(102)

我正在尝试创建包含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;
}

如何将其转换为流,返回服务列表?

6vl6ewon

6vl6ewon1#

像这样改变你的方法:

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;
}

相关问题