Warm tip: This article is reproduced from serverfault.com, please click

dart- Flutter Flutter 的Firestore流映射到另一个流

(dart - flutter firestore stream mapping to another stream)

发布于 2020-11-28 03:21:07

menus在firestore上有一个集合,我想在每个文档上执行 map操作并返回一个新的流。所以Stream<QuerySnapShop>,我想要的不是Stream<VendorMenuItem>

  Stream<VendorMenuItem> getAllVendorMenuItems(String vendorId) async* {
    var collectionReference = fs.collection('restaurants').doc('$vendorId').collection("menus").snapshots();
    collectionReference.map((event) {
      print("mapping");

      event.docs.forEach((element) {
        return VendorMenuItem.fromMap(element.data());
      });
    });
  }

我在构建方法中调用它只是为了测试我的方法,但控制台上什么都没打印出来,这就是我所说的

@override
  Widget build(BuildContext context) {
    var fs = Provider.of<FireStoreDatabaseRoute>(context);

    fs.getAllVendorMenuItems("ewP3B6XWNyqjM98GYYaq").listen((event) {
      print("printing  final result");
      print(event.name);
    });

有什么线索吗?谢谢你

更新:

我没有产生任何结果,但是yield关键字没有帮助

  Stream<VendorMenuItem> getAllVendorMenuItems(String vendorId) async* {
    var collectionReference = FirebaseFirestore.instance.collection('restaurants').doc('$vendorId').collection("menus").snapshots();
    yield* collectionReference.map((event) => event.docs.map((e) => VendorMenuItem.fromMap(e.data())));
  }
Questioner
Brendon Cheung
Viewed
22
Taha Malik 2020-11-28 18:55:28

这就是你使用所使用的方法转换流的方式。

Stream<List<VendorMenuItem>> getAllVendorMenuItems(String vendorId) async* {
    var collectionReference =
        FirebaseFirestore.instance.collection('Files').snapshots();
    yield* collectionReference.map(
      (event) => event.docs
          .map(
            (e) => VendorMenuItem.fromMap(e.data()),
          )
          .toList(), //Added to list to Match the type, other wise dart will throw an error something Like MappedList is not a sub type of List
    );
  }

    

这是使用流控制器来完成相同任务的第二种方法。

  Stream<List<VendorMenuItem>> getAllVendorMenuItems2(String vendorId) {
    StreamController<List<VendorMenuItem>> controller =
        StreamController<List<VendorMenuItem>>();
    FirebaseFirestore.instance.collection("Files").snapshots().listen((event) {
      controller.add(event.docs
              .map(
                (e) => VendorMenuItem.fromMap(e.data()),
              )
              .toList() //ToList To Match type with List
          );
    });

    return controller.stream;
  }