You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
982 B

2 years ago
  1. import 'dart:async';
  2. import 'package:flutter_riverpod/flutter_riverpod.dart';
  3. class TimerNotifier extends StateNotifier<String> {
  4. TimerNotifier() : super('00:00:00');
  5. Timer? _timer;
  6. final _stopwatch = Stopwatch();
  7. @override
  8. void dispose() {
  9. _stopwatch.stop();
  10. _timer?.cancel();
  11. super.dispose();
  12. }
  13. startTimer() {
  14. _stopwatch.start();
  15. _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
  16. state = getDurationString(_stopwatch.elapsed);
  17. });
  18. }
  19. stopTimer() {
  20. _stopwatch.stop();
  21. _stopwatch.reset();
  22. state = getDurationString(_stopwatch.elapsed);
  23. _timer?.cancel();
  24. }
  25. String getDurationString(Duration duration) {
  26. String twoDigits(int n) => n.toString().padLeft(2, "0");
  27. String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
  28. String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
  29. return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
  30. }
  31. }