Last active
April 14, 2021 06:17
-
-
Save angelhdzdev/245b81b674680bd94ba07ddbe2ce7c56 to your computer and use it in GitHub Desktop.
Dart Timer Issue
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
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