Flutter BLoC:使用嵌套StreamBuilders是一种不好的做法吗? [英] Flutter BLoC: Is using nested StreamBuilders a bad practice?
问题描述
是否有更好的方法将小部件暴露给来自不同BLoC的两个或多个流?到目前为止,我一直在使用嵌套的StreamBuilder
用于需要监听的流,就像下面粘贴的代码一样.这是一个好习惯吗?
Is there a better way to expose a widget to two or more streams from different BLoCs? So far I have been using nested StreamBuilder
's for as many streams as I need listening to like the pasted code below. Is this a good practice?
StreamBuilder(
stream: firstBloc.stream1,
builder: (_, AsyncSnapshot snapshot1) {
return StreamBuilder(
stream: secondBloc.stream2,
builder: (_, AsyncSnapshot snapshot2) {
return CustomWidget(snapshot1.data, snapshot2.data);
}
)
}
)
使用像combineLatest2
这样的rxdart
运算符感到笨拙,因为大多数时候我不希望使用其中一个块来了解另一个块中的流.
Using rxdart
operators like combineLatest2
feels clunky since at most times I do not want one of the bloc's being used to be aware of streams in another bloc.
推荐答案
否则,您无法使用小部件进行操作.那是窗口小部件系统的局限性之一:事情往往会变得很嵌套
You cannot do otherwise using widgets. That's one of the limitations of the widget system: things tend to get pretty nested
不过,有一个解决方案:Hooks是React的一项新功能,它通过 flutter_hooks 移植到Flutter (我是维护者).
There's one solution though: Hooks, a new feature coming from React, ported to Flutter through flutter_hooks (I'm the maintainer).
最终结果变为:
final snapshot1 = useStream(firstBloc.stream1);
final snapshot2 = useStream(secondBloc.stream2);
return CustomWidget(snapshot1.data, snapshot2.data);
这就像两个嵌套的StreamBuilder
一样,但是所有的事情都在没有嵌套和没有嵌套的情况下完成.
This behaves exactly like two nested StreamBuilder
, but everything is done within the same without and without nesting.
这篇关于Flutter BLoC:使用嵌套StreamBuilders是一种不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!