Created
April 21, 2023 05:32
-
-
Save caseycrogers/b0c45246194ce4a76f4803c7414fb7b6 to your computer and use it in GitHub Desktop.
A CountDown Timer Because Dart Team Couldn't Be Bothered
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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