Ad

Create An Instance Of Bloc By BlocProvider In InitState In Flutter

- 1 answer

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();
  }
Ad

Answer

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.

Ad
source: stackoverflow.com
Ad