skip to Main Content

I’m implementing BLOC in my project. I have been used it quite a lot in my other projects. The code works in my other project but not on my new project.

This is my code:

  Widget _buildEvents() {
    return BlocProvider<EventBloc>(
      create: (_) => EventBloc(),
      child: BlocBuilder(
        builder: (context, state) {
          return Container();
        },
      ),
    );
  }

The error is:

The following ProviderNotFoundException was thrown building _InheritedProviderScope<EventBloc?>(value: <not yet loaded>):

Error: Could not find the correct Provider<StateStreamable<Object?>> above this BlocBuilder<StateStreamable<Object?>, Object?> Widget

This happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:

- You added a new provider in your `main.dart` and performed a hot-reload.
  To fix, perform a hot-restart.

- The provider you are trying to read is in a different route.

  Providers are "scoped". So if you insert of provider inside a route, then
  other routes will not be able to access that provider.

- You used a `BuildContext` that is an ancestor of the provider you are trying to read.

  Make sure that BlocBuilder<StateStreamable<Object?>, Object?> is under your MultiProvider/Provider<StateStreamable<Object?>>.
  This usually happens when you are creating a provider and trying to read it immediately.

I wonder what did I do wrong because I think the code is already correct. Any help would be appreciated, thank you!

2

Answers


  1. If you are providing a bloc to an immediate child using the bloc, then it won’t find the bloc provided in the widget tree, and then it will throw an error.

    You have two options here.

    1.) Provide a bloc there when you navigate to this screen.

    2.) If you want to provide bloc on the screen, then you have to wrap your child with the Builder widget.

    Login or Signup to reply.
  2. The problem here is the context you use its parent should have the Bloc Provider, In the Bloc Builder there is an option to add your bloc using bloc parameter.

    BlocBuilder< EventBloc, EventState>(
        key: blocBuilder,
        bloc: EventBloc(),
    )
    

    You can declare your EventBloc above and then pass it to the bloc parameter and then use the bloc object to trigger events. Then you won’t need a provider.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search