【问题标题】:Dart/Flutter - "yield" inside a callback functionDart/Flutter - 回调函数中的“yield”
【发布时间】:2019-09-20 05:39:45
【问题描述】:

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

我的问题与这里解决的问题非常相似: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】:

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

    另外 - 当您产生仍在内部流回调中填充的 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;
      }
    }
    

    【讨论】:

    • 谢谢 Nate,完美的答案。不知道await for,但这解决了我的问题。
    • 如何使用这个等待实时更新?
    猜你喜欢
    • 2019-11-28
    • 1970-01-01
    • 2021-05-03
    • 2021-08-29
    • 1970-01-01
    • 2020-02-22
    • 2020-08-15
    • 2018-12-03
    • 2021-03-13
    相关资源
    最近更新 更多