I have this code for listening to bloc on my screen.
late MyBloc myBloc;
@override
void initState() {
print('inside init state');
super.initState();
myBloc = BlocProvider.of<MyBloc>(context);
myBloc.stream.listen((state) {
if (state is MyAddCompletedState) {
print('listening to bloc');
}
}
}
If I add an event, it will print listening to bloc once. If I go to another screen and return to this same screen, it will print listening to bloc twice. It seems like the first listen I did was still active. Next, I tried to close the bloc on my dispose thinking that it would stop the first listen. So that when I come back to the screen it will have a fresh listen but it will have an error: Bad state: Cannot add new events after calling close. I tried to research about this and some mention to dispose the bloc but it doesn't have that syntax anymore. Please help on how to properly close or stop it from listening once I have change screen. Thanks!
//this is found on my screen
late MyBloc myBloc;
@override
void initState() {
print('inside init state');
super.initState();
myBloc = BlocProvider.of<MyBloc>(context);
myBloc.stream.listen((state) {
if (state is MyAddCompletedState) {
print('listening to bloc');
}
}
}
@override
void dispose() {
myBloc.close();
// myBloc.dispose(); --> I saw some tutorial to use this but it doesn't work
super.dispose();
}
This is on my main.dart:
return FutureBuilder(
future: InitFirst.instance.initialize(),
builder: (context, AsyncSnapshot snapshot) {
return MultiBlocProvider(
providers: [
BlocProvider<MyBloc>(
create: (context) => MyBloc(
authenticationRepository: authenticationRepository,
userDataRepository: userDataRepository,
),
),
...
This is the part where I trigger the event. After this event run, the stream.listen will get triggered. But it will be triggered multiple times every time I visit the my screen.
myBloc.add(MyAddEvent(
selectedName,
selectedCount);
Additional note: this event is triggering an update in Firebase which I need to check if it got completed that is why I do the stream.listen.
initState
. Would you try to use BlocListener? – Genevivegenevra