Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Dart 飞镖/颤振-“飞镖”;“收益率”;在回调函数中_Dart_Flutter_Google Cloud Firestore_Dart Async - Fatal编程技术网

Dart 飞镖/颤振-“飞镖”;“收益率”;在回调函数中

Dart 飞镖/颤振-“飞镖”;“收益率”;在回调函数中,dart,flutter,google-cloud-firestore,dart-async,Dart,Flutter,Google Cloud Firestore,Dart Async,我需要为一个函数生成一个列表;但是,我想从回调函数中生成列表,而回调函数本身就在主函数中——这会导致yield语句不针对主函数执行,而是针对回调函数执行 我的问题与这里解决的问题非常相似:但我不能使用补全符,因为我需要让步而不是回报 下面的代码应该更好地描述问题: Stream<List<EventModel>> fetchEvents() async* { //function [1] Firestore.instance .collection

我需要为一个函数生成一个列表;但是,我想从回调函数中生成列表,而回调函数本身就在主函数中——这会导致yield语句不针对主函数执行,而是针对回调函数执行

我的问题与这里解决的问题非常相似:但我不能使用补全符,因为我需要让步而不是回报

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

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]
    });
  }
Stream fetchEvents()异步*{//函数[1]
Firestore.instance
.collection(“事件”)
.getDocuments()
.asStream()
.listen((快照)异步*{//函数[2]
List=List();
snapshot.documents.forEach((文档){
add(EventModel.fromJson(document.data));
});
屈服列表;//这就是我的问题所在-我需要屈服于函数[1]而不是[2]
});
}

而不是
。收听处理另一个函数内部事件的
,您可以使用
等待
来处理外部函数内部的事件

单独-当您生成仍在内部流回调中填充的
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;
  }
}
Stream fetchEvents()异步*{
最终快照=
Firestore.instance.collection('events').getDocuments().asStream();
等待(快照中的最终快照){
//'await.toList()`确保完整列表已准备就绪
//在顺流而下之前
最终事件=等待快照。文档
.map((document)=>EventModel.fromJson(document.data))
.toList();
产量事件;
}
}

谢谢你,内特,完美的答案。不知道
wait for
,但这解决了我的问题。如何使用此wait进行实时更新?