I'm using this package: https://pub.dartlang.org/packages/bloc .
I have 2 views: In the first one I display a list of elements using "bloc1" and, trough a FloatingActionButton, I can navigate to a second screen that uses "bloc2". In this second screen I want to add an element to my previous list trough a Bloc provider of "bloc1", so that I can do something like bloc1.dispatch(addElement)
.
My question is: how can I declare a bloc provider of bloc1?
For example something like:
Bloc bloc = BlocProvider.of<Bloc1>(context)
Asked
Active
Viewed 997 times
0

creativecreatorormaybenot
- 114,516
- 58
- 291
- 402

Little Monkey
- 5,395
- 14
- 45
- 83
2 Answers
1
You would need to wrap your MaterialApp with BlocProvider like:
BlocProvider(bloc: bloc1, child: MaterialApp(...));
Then you can access bloc1 from anywhere using:
BlocProvider.of<Bloc1>(context)
Hope that helps!

Felix Angelov
- 369
- 2
- 6
-
Wouldn't wrapping the entire page widget, let alone the whole `MaterialApp`, in a `BlocProvider` cause performance issues? – Tom Mar 04 '19 at 11:40
-
No there should not be any performance issues. Only the portions of the UI that you wrap with BlocBuilder will rebuild regardless of how high the BlocProvider is in the tree. The main thing to keep in mind is you should always scope the bloc to only the portion of the widget tree that needs it. – Felix Angelov Aug 21 '19 at 04:25
0
Bloc now supports MultiBlocProvider which helps you setup all your blocs once in the main and use it anywhere in your code.
In your main.dart
return MultiBlocProvider(
providers: [
BlocProvider<BlocA>(create: (BuildContext context) => BlocA(),),
BlocProvider<BlocB>(create: (BuildContext context) => BlocB(),),
],
child: MaterialApp(....),
)