简体   繁体   English

Flutter stream 如何在stream中拨打function

[英]Flutter stream how to call function in stream

I have stream like this我有这样的 stream

        StreamBuilder<QuerySnapshot>(
          stream: FireStoreGlobalService().getRooms(globalProviderState.getID),
            builder: (BuildContext context,
                AsyncSnapshot<QuerySnapshot> snapshot) {
              if (!snapshot.hasData) {
                return new Text("Loading");
              }
              
              return Container();
            }),

Function code is Function 密码是

 Future<Stream> getRooms(id) async{
     return FirebaseFirestore.instance
                    .collection(ROOM_COLLECTION)
                    .where(id)
                    .snapshots();
  }

Its showing error on stream它在 stream 上显示错误

The argument type 'Future<Stream<dynamic>>' can't be assigned to the parameter type 'Stream<QuerySnapshot<Object?>>?'

IF i use it like this如果我这样使用它

stream : FirebaseFirestore.instance.collection(ROOM_COLLECTION).where(id).snapshots()

then its working I want to use this as function I think I need to change function type Future But don't know how to fix this.然后它的工作 我想将它用作 function 我想我需要更改 function type Future 但不知道如何解决这个问题。

You can create a Stream block directly instead of creating it as a Future like:您可以直接创建一个 Stream 块,而不是像这样将其创建为 Future :

You don't have to use stream.periodic.您不必使用 stream.periodic。 You can visit the official page of flutter for alternatives:)您可以访问flutter的官方页面以获取替代方案:)

https://api.flutter.dev/flutter/dart-async/Stream-class.htmlhttps://api.flutter.dev/flutter/dart-async/Stream-class.html

 var _dataStream = Stream.periodic(const Duration(seconds: 1), (x) 
 {
   // Your Action Here
   return FirebaseFirestore.instance
                .collection(ROOM_COLLECTION)
                .where(id)
                .snapshots();
 }),

and use it in StreamBuilder并在 StreamBuilder 中使用它

      StreamBuilder<QuerySnapshot>(
        stream: _dataStream,
        builder: (BuildContext context,
            AsyncSnapshot<QuerySnapshot> snapshot) {
          if (!snapshot.hasData) {
            return new Text("Loading");
          }
          
          return Container();
      }),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM