It may sound tricky to stop a timer app in bloc. In fact it’s easy. First you have to understand why your BLoC started to run the timer app?
It’s because you triggered an event. That event emitted a state, and because of that state we were able to start the timer.
First we emitted a state and inside Timer.periodic we started ticking or increasing the value of the time. Before we did that, we did a conditional check of the state.
onTick(Timer timer){
if(state is WorkoutInProgress){
WorkoutInProgress wip = state as WorkoutInProgress;
if(wip.elapsed!< wip.workout!.getTotal()){
emit(WorkoutInProgress(wip.workout, wip.elapsed!+1));
//print("...my elapsed time is ${wip.elapsed}");
}else{
_timer!.cancel();
Wakelock.disable();
emit(const WorkoutInitial());
}
}
}
startWorkout(Workout workout, [int? index]){
Wakelock.enable();
if(index != null){
}else{
emit(WorkoutInProgress(workout, 0));
}
_timer = Timer.periodic(const Duration(seconds: 1), onTick);
}
See how we check on the onTick() method each time we make a tick with the timer.
We always check the state, then make an increment on the current value.
So it means, if we want to stop the timer, just trigger another state. Each time only one state is active. So the timer won’t run.
So just create a new event(BLoC) or method(Cubit) and trigger that event from UI and then emit a new state.