Flutter:将两个 Streams 流式传输到一个屏幕中? [英] Flutter : stream two Streams into a single screen?
问题描述
我有两个流从两个不同的 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);
},
);
}
由于主要的小部件构建方法将带有 resultoutstream 的 StreamBuilder 小部件作为流.我在哪里获取其他流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:将两个 Streams 流式传输到一个屏幕中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!