Bloc: MultiBloc provider and MultiBloc listener issue

Created on 2 Aug 2020  路  5Comments  路  Source: felangel/bloc

I have an app, which has 3 pages that communicate with each other. I have wrapped the first widget with MultiBlocProvider
Screen Shot 2020-08-03 at 1 25 43 AM

I have also wrapped the first widget with BlocConsumer and it works fine.

Screen Shot 2020-08-03 at 1 27 31 AM

In my second screen details.dart, I have wrapped it using a MultiBlocListener as your Counter and Random example

Screen Shot 2020-08-03 at 1 29 48 AM

When I move to this page using Navigator.push( ... ) from my first page, I get the following error

Screen Shot 2020-08-03 at 1 34 14 AM

_Originally posted by @chethanjkulkarni in https://github.com/felangel/bloc/issues/74#issuecomment-667718435_

question

Most helpful comment

Thank you @felangel . All working fine now

All 5 comments

Hi @chethanjkulkarni 馃憢
Thanks for opening an issue!

This is because when you navigate to a new route (Navigator.of(context).push(...)), the new BuildContext doesn't have access to the previous widgets. To solve this you can wrap your MaterialPageRoute in a BlocProvider.value to re-provide the existing bloc to the new route:

ListTile(
  onTap: () {
    Navigator.of(context).push(MaterialPageRoute(
      builder: (_) {
        return BlocProvider.value(value: context.bloc<InvoiceBloc>(), child: Details(...));
      }
  },
)

You can refer to the bloc access recipe for more information 馃憤

How do I pass multiple BlocProviders inside Blocprovider.value(), because when I try to access the one of the bloc provided in MultiBlocProvider in the third page, I get the same error mentioning that the current bloc has no ancestor of previous bloc ?

You can use MultiBlocProvider with BlocProvider.value like:

MultiBlocProvider(
  providers: [
    BlocProvider.value(value: context.bloc<InvoiceBloc>()),
    BlocProvider.value(value: context.bloc<InvoiceDetailsBloc>()),
    BlocProvider.value(value: context.bloc<EditInvoiceBloc>()),
  ],
  child: Details(...),
);

Thank you @felangel . All working fine now

Hi, @felangel
I am using a bloc across 4 different screens(stacked one after another), and quite weird, when I change the state at 4th screen, my first screen doesn't get updated according to the new state
Note: I am not creating a new context for every navigation, but passing the same context using

BlocProvider.value(
     value: BlocProvider.value<ProfileBloc>(context),
     child: ...
)

Is there something I am doing wrong here ?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nerder picture nerder  路  3Comments

rsnider19 picture rsnider19  路  3Comments

frankrod picture frankrod  路  3Comments

nhwilly picture nhwilly  路  3Comments

timtraversy picture timtraversy  路  3Comments