create an instance of Bloc by BlocProvider in initState in flutter


is it a good practice to initialize and create instance of Bloc in InItState() method in statefulWidget? or not, and why, thank you:

LoginBloc loginBloc;

  void initState() {
    loginBloc = BlocProvider.of<LoginBloc>(context);


The code you’ve written is not actually instantiating any object. It’s retrieving any instance of LoginBloc available from the context provided so It’s totally OK to do that. However as far as I know it’s OK to even instantiate objects inside initState but keep in mind that after creating instance out of BlocProvider, you have to deal with closing it too.

Answered By – Amir_P

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *