Flutter:将两个流串流到一个屏幕中? [英] Flutter : stream two Streams into a single screen?

查看:86
本文介绍了Flutter:将两个流串流到一个屏幕中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个从两个不同的api获取的流。

I have two streams fetching from two different api.

Stream<Month> get monthOutStream => monthOutController.stream;
Stream<MySchedule> get resultOutStream => resultController.stream;

我正在应用程序的两种不同状态下获取这些数据,这些结果在开始时和几个月后

I am fetching these data at two different state of the application, result at the begining and Months after some events from user.

MyScheduleBloc(){
  initialData();
}

Future initialData() async {
  MySchedule mySchedule = await myScheduleViewModel.importMySchedule(now.id);
  resultController.add(mySchedule);
}

我的屏幕上有一个流生成器,

My screen has a streambuilder as

Widget build(BuildContext context) {
final webCalenderBloc = WebCalenderBloc();
return StreamBuilder(
  stream: webCalenderBloc.resultOutStream,
  builder: (BuildContext context , snapdata){
    if(!snapdata.hasData){
      return Center(
        child: CircularProgressIndicator(),
      );
    }
    return body(snapdata.data);
   },
 );
}

由于主窗口小部件构建方法将StreamBuilder窗口小部件与resultoutstream作为流。我在哪里获取其他流monthoutStream。
我可以在流中获取流吗?我在处理两个流时是否缺少任何内容。我不想从monthoutstream构建任何小部件,但希望检查其中的数据。

Since the main widget build method took the StreamBuilder Widget with resultoutstream as a stream.Where do i fetch the other stream monthoutStream. Can i fetch stream inside a stream? Do i missing anything while handling two stream.I dont want to build any widget from monthoutstream but want to check the data inside it.

推荐答案

如果需要,您可以嵌套 StreamBuilder 。没有什么可以阻止您执行以下操作:

You can nest StreamBuilder if needed. Nothing prevents you from doing the following:

StreamBuilder(
  stream: stream1,
  builder: (context, snapshot1) {
    return StreamBuilder(
      stream: stream2,
      builder: (context, snapshot2) {
        // do some stuff with both streams here
      },
    );
  },
)

另一个解决方案对您而言有意义的是:流被设计为可合并/转换的。您可以创建第三个流,该流是后面两个流的合并。

Another solution if this makes sense for you is: Streams are designed to be mergeable/transformed. You could make a third stream that is a merge of the two later streams.

理想情况下,对于复杂的流操作,您将要使用 rxdart ,因为它提供了一些有用的转换器。

Ideally for complex stream operations you'll want to use rxdart as it provides a few useful transformer.

使用rxdart,将两个 Observable (其中是 Stream 的子类)

Using rxdart, the fusion of two Observable (which are subclass of Stream) would be the following:

Observable<bool> stream1;
Observable<String> stream2;

final fusion = stream1.withLatestFrom(stream2, (foo, bar) {
  return MyClass(foo: foo, bar: bar);
});

这篇关于Flutter:将两个流串流到一个屏幕中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆