89 lines
2.2 KiB
Dart
89 lines
2.2 KiB
Dart
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|
import 'package:wakelock_plus/wakelock_plus.dart';
|
|
import 'package:just_audio/just_audio.dart';
|
|
|
|
final timerProvider = StateNotifierProvider<TimerNotifier, TimerState>((ref) {
|
|
return TimerNotifier();
|
|
});
|
|
|
|
class TimerState {
|
|
final Duration remaining;
|
|
final bool isRunning;
|
|
final int selectedMinutes;
|
|
|
|
TimerState({
|
|
this.remaining = Duration.zero,
|
|
this.isRunning = false,
|
|
this.selectedMinutes = 15, // Default
|
|
});
|
|
|
|
TimerState copyWith({
|
|
Duration? remaining,
|
|
bool? isRunning,
|
|
int? selectedMinutes,
|
|
}) {
|
|
return TimerState(
|
|
remaining: remaining ?? this.remaining,
|
|
isRunning: isRunning ?? this.isRunning,
|
|
selectedMinutes: selectedMinutes ?? this.selectedMinutes,
|
|
);
|
|
}
|
|
}
|
|
|
|
class TimerNotifier extends StateNotifier<TimerState> {
|
|
TimerNotifier() : super(TimerState());
|
|
|
|
DateTime? _endTime;
|
|
final AudioPlayer _audioPlayer = AudioPlayer();
|
|
|
|
void setMinutes(int minutes) {
|
|
state = state.copyWith(selectedMinutes: minutes);
|
|
}
|
|
|
|
void start() {
|
|
final duration = Duration(minutes: state.selectedMinutes);
|
|
_endTime = DateTime.now().add(duration);
|
|
state = state.copyWith(remaining: duration, isRunning: true);
|
|
WakelockPlus.enable();
|
|
|
|
// Sound vorbereiten (später Asset hinzufügen)
|
|
_audioPlayer.setAsset('assets/sounds/alarm.mp3').catchError((_) {});
|
|
}
|
|
|
|
void pause() {
|
|
state = state.copyWith(isRunning: false);
|
|
}
|
|
|
|
void stop() {
|
|
state = TimerState(selectedMinutes: state.selectedMinutes); // Reset remaining + running
|
|
_endTime = null;
|
|
WakelockPlus.disable();
|
|
_audioPlayer.stop();
|
|
}
|
|
|
|
void tick() {
|
|
if (!state.isRunning || _endTime == null) return;
|
|
|
|
final now = DateTime.now();
|
|
if (now.isAfter(_endTime!)) {
|
|
state = state.copyWith(remaining: Duration.zero, isRunning: false);
|
|
WakelockPlus.disable();
|
|
_playAlarm();
|
|
return;
|
|
}
|
|
|
|
state = state.copyWith(remaining: _endTime!.difference(now));
|
|
}
|
|
|
|
Future<void> _playAlarm() async {
|
|
await _audioPlayer.seek(Duration.zero);
|
|
await _audioPlayer.play();
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
WakelockPlus.disable();
|
|
_audioPlayer.dispose();
|
|
super.dispose();
|
|
}
|
|
} |