Skip to content

Instantly share code, notes, and snippets.

@angelhdzdev
Last active April 14, 2021 06:17
Show Gist options
  • Save angelhdzdev/245b81b674680bd94ba07ddbe2ce7c56 to your computer and use it in GitHub Desktop.
Save angelhdzdev/245b81b674680bd94ba07ddbe2ce7c56 to your computer and use it in GitHub Desktop.
Dart Timer Issue
import "dart:async";
class SimpleTimer {
bool looping = false;
final int delay;
int _to = 0;
int _currentCount = 0;
late Timer _timer;
final _controller = StreamController<int>();
Stream<int> get onTick => _controller.stream;
SimpleTimer({required this.delay});
void from(int value) {
_currentCount = value;
}
void to(int value) {
_to = value;
_timer = Timer.periodic(Duration(milliseconds: delay), _tick);
}
void _tick(Timer timer) {
if (_currentCount > _to) {
_timer.cancel();
return;
}
_controller.sink.add(_currentCount);
_currentCount ++;
}
int get currentCount => _currentCount;
}
void main() {
//Usage
final timer = SimpleTimer(delay: 1000);
timer.onTick.listen((int currentCount) {
print("Tick! ${currentCount}");
});
timer..from(1)..to(20);
/*
NOTE: After running the app once and the timer starts, hit the RUN button many times.
It will keep creating new instances of timers instead of stopping the current timers.
It feels like the RUN button does a Soft Reset instead of a Full Restart.
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment