简体   繁体   中英

Flutter BLoC: Is using nested StreamBuilders a bad practice?

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.

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.

您可以将它们放在应用程序顶部的 MultiBlocProvider 中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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