So I want to write a BlocListener inside initState(), which functions to provide logic on whether a code should be executed or not based on the current state, like this:
@override
void initState() {
super.initState();
BlocListener<InternetCubit, InternetState>(
listener: (context, stateInt) {
if (stateInt is InternetConnectedState) {
print('connected');
} else if (stateInt is InternetNotConnectedState) {
print('not connected');
}
},
);
}
I’ve called this function right at the start of the application launch, and this code can work wherever and whenever an event occurs (in this case whether there is an internet connection or not) like this:
context.read<InternetCubit>().isInternetConnected();
But the code does not run or is not called.
I’ve tried doing research, but I’ve only found 1 piece of information]1 that says:
BlocListener only receives updates after it is mounted in the widget
Does using BlocListener only apply to Widgets, and not work in initState()?
Am I wrong in understanding the concept?
Thank you, please help..
3
Answers
Yes. You cannot call the bloc in that way. BlocListener is mainly used in the build method that is after mounting in the widget.
One way would be. Use BlocListener inside the build method of the widget.
Now I assume you want to do implement that in the initstate.
We can use the concept of streamsubscription.
In the stateful widget. Declare a Stream Subscription
In the initstate() call the cubit and add listener to its stream
In the dispose method do not forget to cancel the stream:
Note: Both are the ways you can access your cubit. And there may be many but this would suffice.
You can use the
stream
property ofCubit
like this:You can use BlocConsumer which provides
listener
. If it is about building ui based on state or state dataBlocBuilder
s state is fine.