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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With