Dart/Flutter - “yield” inside a callback function

后端 未结 1 1748
北荒
北荒 2021-01-02 02:04

I need to yield a list for a function; however, I want to yield the list from within a callback function, which itself is inside the main function - this results in the yiel

1条回答
  •  生来不讨喜
    2021-01-02 03:03

    Instead of .listen which handles events inside another function you can use await for to handle events inside the outer function.

    Separately - you might want to reconsider the pattern when you yield List instances that are still getting populated inside an inner stream callback...

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

    0 讨论(0)
提交回复
热议问题