Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 662
Ali Amin Avatar asked Oct 17 '22 06:10

Ali Amin


1 Answers

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.

like image 142
Rémi Rousselet Avatar answered Oct 20 '22 17:10

Rémi Rousselet