I want to break a for loop inside a bloc. I am using a bool named _isRunning
to control my for loop. But Other events are not executing while my for loop is running and causing _isRunning
bool to change its value after the for loop is finished executing. How can I stop for loop inside a bloc?
class myBloc extends Bloc<myEvent, myState> {
myBloc() : super(Stopped());
var _isRunning = false;
@override
Stream<myState> mapEventToState(myEvent event) async* {
if (event is Start) {
_isRunning = true;
yield Running();
for (var i = 0; index < 10; i++) {
if (_isRunning) {
print('$i');
await Future.delayed(const Duration(seconds: 1), () => null);
} else {
break;
}
}
yield Stopped();
}
if (event is Stop) {
_isRunning = false;
yield Stopped();
}
}
}
I believe your problem should be fixed by moving the for-loop into an asynchronous method and then adding a stopped event within that method
class myBloc extends Bloc<myEvent, myState> {
myBloc() : super(Stopped());
var _isRunning = false;
@override
Stream<myState> mapEventToState(myEvent event) async* {
if (event is Start) {
_isRunning = true;
yield Running();
_asyncMethod(); // no await here
}
if (event is Stop) {
_isRunning = false;
yield Stopped();
}
}
Future<void> _asyncMethod() async {
for (var i = 0; i < 10; i++) {
if (_isRunning) {
print('$i');
await Future.delayed(const Duration(seconds: 1), () => null);
} else {
break;
}
}
add(stop())
}
}
Bloc adds every event into a queue and deals with each one by one in order, which means that it will ignore the stop event until the start event is over. However, dart will never wait for an async method to complete unless explicitly told so (with an await) so moving all the code into an async method lets it run at its own pace.