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:
bloc/cubit object inside the StatefulWidget ?myCubit.add(OnPageStart(id)) inside the StatefulWidget ?Hi @samramez 馃憢
initState you would need to provide your bloc above your StatefulWidget, or else it will not be accessible.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 馃憤
Most helpful comment
@samramez the recommended approach is to wrap your widget in a
BlocProviderto provide the bloc instance to the children. Then you can access them viaBlocProvider.of<MyBloc>(context)orcontext.bloc<MyBloc>(). This ensures you don't have to worry about memory leaks because theBlocProviderwill 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 馃憤