Flutter: BLoC package – bloc provider

Issue

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)

Solution

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!

Answered By – Felix Angelov

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.