Dart / Flutter - 回调函数中的“yield”

问题描述 投票:0回答:1

我需要为函数生成一个列表;但是,我想从回调函数中产生列表,回调函数本身在main函数内部 - 这导致yield语句不是为main函数执行,而是为回调函数执行。

我的问题非常类似于这里解决的问题:Dart Component: How to return result of asynchronous callback?但我不能使用Completer因为我需要屈服而不是返回。

下面的代码应该更好地描述问题:

Stream<List<EventModel>> fetchEvents() async* { //function [1]
    Firestore.instance
        .collection('events')
        .getDocuments()
        .asStream()
        .listen((snapshot) async* { //function [2]
      List<EventModel> list = List();
      snapshot.documents.forEach((document) {
        list.add(EventModel.fromJson(document.data));
      });

      yield list; //This is where my problem lies - I need to yield for function [1] not [2]
    });
  }
dart flutter google-cloud-firestore dart-async
1个回答
3
投票

而不是处理另一个函数内的事件的.listen,您可以使用await for来处理外部函数内的事件。

另外 - 当你产生仍在内部流回调中填充的List实例时,你可能想重新考虑这个模式......

Stream<List<EventModel>> fetchEvents() async* {
  final snapshots =
      Firestore.instance.collection('events').getDocuments().asStream();
  await for (final snapshot in snapshots) {
    // The `await .toList()` ensures the full list is ready
    // before yielding on the Stream
    final events = await snapshot.documents
        .map((document) => EventModel.fromJson(document.data))
        .toList();
    yield events;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.