Fixed timer issue

This commit is contained in:
Abdullah Alassaf
2024-06-23 02:34:10 +03:00
parent 47639c0cb9
commit 28678be844
3 changed files with 138 additions and 102 deletions

View File

@ -1,5 +1,4 @@
import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/three_gang_bloc/three_gang_event.dart';
import 'package:syncrow_app/features/devices/bloc/three_gang_bloc/three_gang_state.dart';
@ -24,6 +23,7 @@ class ThreeGangBloc extends Bloc<ThreeGangEvent, ThreeGangState> {
on<SetCounterValue>(_setCounterValue);
on<GetCounterEvent>(_getCounterValue);
on<TickTimer>(_onTickTimer);
on<OnClose>(_onClose);
}
void _fetchThreeGangStatus(InitialEvent event, Emitter<ThreeGangState> emit) async {
@ -135,8 +135,11 @@ class ThreeGangBloc extends Bloc<ThreeGangEvent, ThreeGangState> {
void _setCounterValue(SetCounterValue event, Emitter<ThreeGangState> emit) async {
emit(LoadingNewSate(threeGangModel: deviceStatus));
int seconds = 0;
try {
int seconds = (event.duration.inHours * 60 * 60) + (event.duration.inMinutes * 60);
// The CupertinoTimerPicker widget increments by 60 minutes when the hours are increased.
int min = event.duration.inMinutes - event.duration.inHours * 60;
seconds = (event.duration.inHours * 60 * 60) + (min * 60);
final response = await DevicesAPI.controlDevice(
DeviceControlModel(deviceId: threeGangId, code: event.deviceCode, value: seconds),
threeGangId);
@ -149,9 +152,20 @@ class ThreeGangBloc extends Bloc<ThreeGangEvent, ThreeGangState> {
} else if (event.deviceCode == 'countdown_3') {
deviceStatus.thirdCountDown = seconds;
}
} else {
emit(const FailedState(error: 'Something went wrong'));
return;
}
} catch (_) {}
emit(UpdateState(threeGangModel: deviceStatus));
} catch (e) {
emit(FailedState(error: e.toString()));
return;
}
if (seconds > 0) {
_onStartTimer(seconds);
} else {
_timer?.cancel();
emit(TimerRunComplete());
}
}
void _getCounterValue(GetCounterEvent event, Emitter<ThreeGangState> emit) async {
@ -183,6 +197,10 @@ class ThreeGangBloc extends Bloc<ThreeGangEvent, ThreeGangState> {
}
}
void _onClose(OnClose event, Emitter<ThreeGangState> emit) {
_timer?.cancel();
}
void _onStartTimer(int seconds) {
_timer?.cancel();
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {

View File

@ -77,3 +77,5 @@ class TickTimer extends ThreeGangEvent {
}
class StopTimer extends ThreeGangEvent {}
class OnClose extends ThreeGangEvent {}