Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.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
Firebase 订阅一条流,然后用飞镖将其转发_Firebase_Flutter_Dart_Google Cloud Firestore_Dart Stream - Fatal编程技术网

Firebase 订阅一条流,然后用飞镖将其转发

Firebase 订阅一条流,然后用飞镖将其转发,firebase,flutter,dart,google-cloud-firestore,dart-stream,Firebase,Flutter,Dart,Google Cloud Firestore,Dart Stream,我使用firestore订阅流,如下所示: db.collection(collection).snapshots().listen((QuerySnapshot snapshot) { // something }); listen返回一个StreamSubscription 现在我想写一个方法,就是订阅这个流,这样当我得到新的结果时我就可以做一些事情了。但是同样的方法应该自己返回一个数据流。我试过这个: static Stream<QuerySnapshot> listen

我使用firestore订阅流,如下所示:

db.collection(collection).snapshots().listen((QuerySnapshot snapshot) {
  // something
});
listen返回一个StreamSubscription

现在我想写一个方法,就是订阅这个流,这样当我得到新的结果时我就可以做一些事情了。但是同样的方法应该自己返回一个数据流。我试过这个:

static Stream<QuerySnapshot> listenOnCollection(String collection) async* {
    db.collection(collection).snapshots().listen((QuerySnapshot snapshot) {
      // do something and now forward incoming snapshot
      yield snapshot;
    });
  }

这是行不通的,因为收益率在内部环境中是未知的。我怎样才能做到这一点?非常感谢

您可以映射和转换流,然后返回它:

static Stream<QuerySnapshot> listenOnCollection(String collection){
  return db.collection(collection).snapshots().map((QuerySnapshot snapshot) {
     // do something and now forward incoming snapshot
     return snapshot;
  });
}

您可以映射和转换流,然后将其返回:

static Stream<QuerySnapshot> listenOnCollection(String collection){
  return db.collection(collection).snapshots().map((QuerySnapshot snapshot) {
     // do something and now forward incoming snapshot
     return snapshot;
  });
}
测试,工作

static Stream<QuerySnapshot> listenOnCollection(String collection) async* {
    var stream = db.collection(collection).snapshots();
    await for(final snapshot in stream){
        yield snapshot;
    }
}
测试,工作

static Stream<QuerySnapshot> listenOnCollection(String collection) async* {
    var stream = db.collection(collection).snapshots();
    await for(final snapshot in stream){
        yield snapshot;
    }
}