问题
I would like to know the best way to pass the bloc. I read about the bloc providers, but what`s the difference between using them and just passing the bloc in the constructor like:
ExampleView X = ExampleView(bloc,...)
Actually I find this way easier to test and also a better way to keep the code cleaner. For example, if I have more blocs, something like this can happen:
XBlocProvider(
bloc: XBloc,
child: YBlocProvider(
bloc: Y,
child: ZBlocProvider...
)
or maybe it's just my lack of knowledge. So, which ones are the benefits?
回答1:
The problem with this:
ExampleView X = ExampleView(bloc,...)
You instantiate the BLoC every time you need, you'll lost all data from old sessions, also it will be extra cost for CPU.
This approach only valid if your bloc is connected with just one specific page but usually, you need a static BLoC. That's why we use InheritedWidget, because Flutter keeps all InheritedWidgets in the memory. With this approach, you instantiate once and using everywhere without losing any session, also efficient in performance wise. Of course you can use singleton but you won't make any friend by doing so :)
There too many approaches but Flutter team just announced they suggest the this package: https://pub.dev/packages/provider
With this package you can inject your multiple blocs like this if you don't want cascaded huge tree:
MultiProvider(
providers: [
Provider<Foo>.value(value: foo),
Provider<Bar>.value(value: bar),
Provider<Baz>.value(value: baz),
],
child: someWidget,
)
At the end, try to comprehend every approach, I especifically suggest you to grasp this article:
https://www.didierboelens.com/2018/12/reactive-programming---streams---bloc---practical-use-cases/
You'll get the idea when to use bloc with provider or as a singleton or instantiate like your example etc.
回答2:
The first difference is how you access your bloc from the widget.
- when you pass it through the constructor you have direct access to it
- when you use BlocProvider then, in most cases depending on your
bloc
implementation, you have obtain it viaProvider
which extendsInheritedWidget
usingcontext
for example:
final xBloc = Provider.of<XBloc>(context);
What's more when you wrap your bloc
with BlocProvider
then your bloc
's scope is limited to this widget's subtree so it can be only accessed by the BlocProvider
s descendants.
回答3:
Not having to pass the bloc in the constructor is the benefit of using the provider. It reduces the complexity of your application by enabling you to propagate information down the widget tree with the help of InheritedWidget. All you just need is to access the bloc from the child widget with BlocProvider.of(context)
.
来源:https://stackoverflow.com/questions/56163563/bloc-how-to-pass-it