Skip to content

Instantly share code, notes, and snippets.

@caseycrogers
Created April 21, 2023 05:32
Show Gist options
  • Save caseycrogers/b0c45246194ce4a76f4803c7414fb7b6 to your computer and use it in GitHub Desktop.
Save caseycrogers/b0c45246194ce4a76f4803c7414fb7b6 to your computer and use it in GitHub Desktop.
A CountDown Timer Because Dart Team Couldn't Be Bothered
class CountdownTimer extends ValueListenable<Duration> with ChangeNotifier {
CountdownTimer(this.duration, {this.frequency});
final Duration duration;
final Duration? frequency;
final Stopwatch _stopwatch = Stopwatch();
Timer? _timer;
bool get timedOut => value == Duration.zero;
bool get isRunning => _timer != null;
void start() {
assert(_timer == null);
// Yeah there's probably like a sub microsecond error here because stopwatch
// and timer aren't initialized in the same CPU cycle, sue me.
_stopwatch.start();
_timer = Timer.periodic(
frequency ?? const Duration(milliseconds: 10),
(t) {
notifyListeners();
},
);
}
void pause() {
_timer?.cancel();
}
void stop() {
_timer?.cancel();
_timer = null;
}
@override
Duration get value {
final Duration timeLeft = duration - _stopwatch.elapsed;
if (timeLeft.isNegative) {
stop();
return Duration.zero;
}
return timeLeft;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment