Bloc: Using context in initState

Created on 11 Apr 2019  路  1Comment  路  Source: felangel/bloc

I was looking in your example and I saw in https://github.com/felangel/bloc/blob/master/examples/flutter_todos/lib/screens/home_screen.dart

_filteredTodosBloc = FilteredTodosBloc(
      todosBloc: BlocProvider.of<TodosBloc>(context),
    );

Is this safe to use the context in initState? Reading the all the documentation around everybody is saying not to use context in initState. Can you explain why is ok using as you did.
I am doing always in didChangeDependencies something like _filteredTodosBloc ??= ...

question

Most helpful comment

Hi @cosinus84 馃憢
Thanks for opening an issue!

Great observation and normally I would recommend accessing inheritedWidgets in didChangeDependencies but with BlocProvider it works in initState because it uses ancestorInheritedElementForWidgetOfExactType combined withupdateShouldNotify(BlocProvider oldWidget) => false;

Normally if you're using inheritFromWidgetOfExactType and support notifying on updates then you wouldn't be able to access it in initState as you mentioned.

Hope that helps and great question 馃挴

>All comments

Hi @cosinus84 馃憢
Thanks for opening an issue!

Great observation and normally I would recommend accessing inheritedWidgets in didChangeDependencies but with BlocProvider it works in initState because it uses ancestorInheritedElementForWidgetOfExactType combined withupdateShouldNotify(BlocProvider oldWidget) => false;

Normally if you're using inheritFromWidgetOfExactType and support notifying on updates then you wouldn't be able to access it in initState as you mentioned.

Hope that helps and great question 馃挴

Was this page helpful?
0 / 5 - 0 ratings

Related issues

clicksocial picture clicksocial  路  3Comments

RobPFarley picture RobPFarley  路  3Comments

craiglabenz picture craiglabenz  路  3Comments

komapeb picture komapeb  路  3Comments

abinvp picture abinvp  路  3Comments