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

tigranhov picture tigranhov  路  3Comments

1AlexFix1 picture 1AlexFix1  路  3Comments

clicksocial picture clicksocial  路  3Comments

nhwilly picture nhwilly  路  3Comments

wheel1992 picture wheel1992  路  3Comments