BlocProvider and MultiBlocProvider

Learn how to use BlocProvider and MultiBlocProvider to provide a BLoC to the widget tree.

The Flutter package flutter_bloc is made to provide Flutter widgets to implement the BLoC pattern without any of the boilerplate code. In this chapter, we’ll go through all the widgets that the flutter_bloc library provides and their use cases.

The BlocProvider widget

The first widget we have is the BlocProvider widget. This is the same widget we manually created in the Putting BLoC Concepts to Use lesson. The flutter_bloc library created this widget for us, so we don’t have to manually create it ourselves for each project.

The BlocProvider allows us to provide a BLoC instance to its child widgets. This makes it easy to access the BLoC’s methods and states from anywhere within the widget tree. To use BlocProvider, make it a parent widget to widgets that require access to the same BLoC instance.

Usage

The simplest usage is to create the BLoC in the create parameter that’s provided by BlocProvider. This parameter expects a function that returns a Bloc. This function provides us with the BuildContext, which can be useful if the BLoC needs access to the current context of our application.

Get hands-on with 1200+ tech skills courses.