Good morning, In my Flutter journal project I have HomeBlocProvider and HomeBloc.
In the Home page I am initializing the HomeBloc in the didChangeDependencies() function but somehow it doesn’t initialize
In the build() I am declaring the variable
HomeBloc? _homeBloc;
and this is the didChangeDependencies()
@override
void didChangeDependencies() {
super.didChangeDependencies();
_homeBloc = HomeBlocProvider.of(context).homeBloc;
}
The body property of the Scaffold() is StreamBuilder() and the stream property of it I am listening to the _homeBloc!.listJournal
When I run the project I got this error
Exception caught by widgets library
The following _CastError was thrown building Home(dirty, state: _HomeState#ada70):
Null check operator used on a null value
So it seems like the homeBloc still null
This is the code of the HomeBlocProvider
class HomeBlocProvider extends InheritedWidget {
const HomeBlocProvider({Key? key, required Widget child, this.homeBloc, this.uid}) : super(key: key, child: child);
@override
bool updateShouldNotify(HomeBlocProvider oldWidget) => homeBloc != oldWidget.homeBloc;
static HomeBlocProvider of(BuildContext context) {
return (context.dependOnInheritedWidgetOfExactType<HomeBlocProvider>() as HomeBlocProvider);
}
final HomeBloc? homeBloc;
final String? uid;
}
I tried to print a string in the didChangeDependecies() and nothing printed so it seems that it doesn’t even execute the function
2
Answers
Have you tried this?
The
didChangeDependencies()
method is called when the dependencies of the widget change, which can happen during the widget’s lifecycle. However, it’s not guaranteed to be called every time the widget is rebuilt.In your case, the
HomeBloc
initialization logic should be placed in theinitState()
method instead ofdidChangeDependencies()
. TheinitState()
method is called exactly once when the widget is inserted into the widget tree.Also, make sure that
HomeBloc
is initialized and provided properly to widget tree.