0

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;

  @override
  void initState() {
    loginBloc = BlocProvider.of<LoginBloc>(context);
    super.initState();
  }
Osama Mohammed
  • 2,433
  • 13
  • 29
  • 61
  • 1
    Yes, this is how you do it. Either create a bloc using default constructor, or get it from BlocProvider - both in initState(). Use bloc.close() in dispose() if the bloc was created just for your widget using consturctor. – Alexey Subbotin Oct 23 '20 at 09:36
  • thank you for your answer, but please can you clarify what do you mean by this (( if the bloc was created just for your widget using consturctor))? – Osama Mohammed Oct 23 '20 at 09:48
  • 1
    Sorry for unclear explanaition. That was just a reminder to close your bloc when its no longer needed, e.g. if its created in initState() and is only used in your widget, then it should be closed when the widget is disposed - so in dispose(). – Alexey Subbotin Oct 24 '20 at 09:48
  • 1
    This is basically what initState() and dispose() are used for. Answering thread question - yes, you should instantiate or get your bloc from provider in initState(). – Alexey Subbotin Oct 24 '20 at 09:50

1 Answers1

1

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.

Amir_P
  • 8,322
  • 5
  • 43
  • 92