Bloc: How to call and use a bloc/cubit on page start inside a StatefulWidget

Created on 8 Sep 2020  路  3Comments  路  Source: felangel/bloc

The scenario I'm looking for is pretty simple but couldn't find any example which addresses that.

I have a StatefulWidget which upon its creation, I wish to make an API call (on page start). Following that, loading appears on the screen and when the result is returned, the StatefulWidget updates accordingly.

My biggest challenge is where and how should I provide my bloc/cubit object.

My immediate assumption was to get the bloc inside initState(); however, if I add final cubit = contex.bloc<MyCubit>(), the context is not able to access the bloc object. (_same approach did not work inside didChangeDependencies()_)

So can you please help me understand:

  1. How can I provide the bloc/cubit object inside the StatefulWidget ?
  2. Where should I add my myCubit.add(OnPageStart(id)) inside the StatefulWidget ?
question

Most helpful comment

@samramez the recommended approach is to wrap your widget in a BlocProvider to provide the bloc instance to the children. Then you can access them via BlocProvider.of<MyBloc>(context) or context.bloc<MyBloc>(). This ensures you don't have to worry about memory leaks because the BlocProvider will handle closing the bloc for you.

Closing for now but feel free to comment with additional questions and I'm happy to continue the conversation 馃憤

All 3 comments

Hi @samramez 馃憢

  1. If you wish to access your cubit/bloc within initState you would need to provide your bloc above your StatefulWidget, or else it will not be accessible.
  2. You can add it in initState as long as your id never changes. If it changes then you might want to trigger your call from didUpdateWidget too.

Thank you @RollyPeres for the response.

So if I understood correctly, you're suggesting that I create the bloc on the parent Widget and pass it to the StatefulWidget's constructor, and then pass it to the State class, correct?

If that's the case, is it safe to store a [assuming] heavy object like bloc as the class field? (memory leak concerns)

@samramez the recommended approach is to wrap your widget in a BlocProvider to provide the bloc instance to the children. Then you can access them via BlocProvider.of<MyBloc>(context) or context.bloc<MyBloc>(). This ensures you don't have to worry about memory leaks because the BlocProvider will handle closing the bloc for you.

Closing for now but feel free to comment with additional questions and I'm happy to continue the conversation 馃憤

Was this page helpful?
0 / 5 - 0 ratings