skip to Main Content

I was using this setup with BlocProvider without any issues, but now i’m creating a page where i need to access 2 different Blocs, as the changes there need to go to 2 different endpoints.
Worst case scenario i’ll create 1 bloc that calls the 2 endpoints but this doesn’t really sound great tbh.
This is what i did. i have a simple button that when pressed leads to the said widget (through a file that i call screen and setup the blocs in)
again, this works fine in the rest of the app where i use simple BlocProviders instead of MultiBlocProviders

onPressed: () => Navigator.push(context,
              MaterialPageRoute(builder: (context) => IncomeExpenseScreen(title:"Income", property: widget.property, expense: null))),

This leads to a screen where i setup the blocs

Widget build(BuildContext context) {
return MultiBlocProvider(
    providers: [
      BlocProvider<PortfolioBloc>(create: (context) => PortfolioBloc()),
      BlocProvider<IncomeAndExpenseBloc>(create: (context) => IncomeAndExpenseBloc()),
    ],
child: IncomeExpenseWidget(title, property, expense),
);

}

This child widget then in it’s init call both blocs to initialize them as

propertyListBloc = BlocProvider.of<PortfolioBloc>(context);
incomeExpenseBloc = BlocProvider.of<IncomeAndExpenseBloc>(context);

But instead of working as expected, i get a red screen and a message on the terminal saying that my context is a dirty girl

    ======== Exception caught by widgets library =======================================================
The following assertion was thrown building Builder:
        BlocProvider.of() called with a context that does not contain a PortfolioBloc.

        No ancestor could be found starting from the context that was passed to BlocProvider.of<PortfolioBloc>().

        This can happen if the context you used comes from a widget above the BlocProvider.

        The context used was: IncomeExpenseWidget(dirty, state: _IncomeExpenseWidgetState#39035(lifecycle state: created))

2

Answers


  1. Chosen as BEST ANSWER

    Turns out the problem was that I was routing directly to the widget instead of through the screen. thus the blocs were never being provided to the context... sorry for wasting your time, I'll have more coffee next time...


  2. I think you just need to pass the bloc instance instead of creating new on new route/page.

    It will be like with BlocProvider.value

    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) => BlocProvider.value(
          value: BlocProvider.of<PortfolioBloc>(context),
          child: YourWidget(),
        ),
      ),
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search