Flutter BLoC: Is using nested StreamBuilders a bad practice?

三世轮回 提交于 2020-05-15 04:21:09

问题


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);
            }
        )
    }
)

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.


回答1:


You cannot do otherwise using widgets. That's one of the limitations of the widget system: things tend to get pretty nested

There's one solution though: Hooks, a new feature coming from React, ported to Flutter through flutter_hooks (I'm the maintainer).

The end result becomes this:

final snapshot1 = useStream(firstBloc.stream1);
final snapshot2 = useStream(secondBloc.stream2);

return CustomWidget(snapshot1.data, snapshot2.data);

This behaves exactly like two nested StreamBuilder, but everything is done within the same without and without nesting.



来源:https://stackoverflow.com/questions/54840870/flutter-bloc-is-using-nested-streambuilders-a-bad-practice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!