How to Check if Timer is Active Before Creating a New One
1,487
Add a check to see if _timer
is already active using the isActive
property of Timer
s. If it's already active, it won't create a new one.
Example:
void startTimer() {
const oneSec = const Duration(seconds: 1);
if(!_timer?.isActive) {
_timer = new Timer.periodic(
oneSec,
(Timer timer) => setState(
() {
if (_start < 1) {
timer.cancel();
} else {
_start = _start - 1;
}
},
),
);
}
}
Author by
Andrew Caprario
Updated on December 21, 2022Comments
-
Andrew Caprario over 1 year
I came across this code for a timer on another thread. When you press the
RaisedButton
multiple times concurrently it adds a -1 second for every click thus increasing the rate of decrease.Any ideas for the easiest way to check if the timer is already active and if it is to not let the
RaisedButton
create a new one. Thanks!import 'dart:async'; [...] Timer _timer; int _start = 10; void startTimer() { const oneSec = const Duration(seconds: 1); _timer = new Timer.periodic( oneSec, (Timer timer) => setState( () { if (_start < 1) { timer.cancel(); } else { _start = _start - 1; } }, ), ); } @override void dispose() { _timer.cancel(); super.dispose(); } Widget build(BuildContext context) { return new Scaffold( appBar: AppBar(title: Text("Timer test")), body: Column( children: <Widget>[ RaisedButton( onPressed: () { startTimer(); }, child: Text("start"), ), Text("$_start") ], ), ); }
-
Andrew Caprario almost 4 yearsI tried your solution and I got it to work however when I used the same logic in my own project, granted it is just a project to help me learn,
if(!_timer?.isActive)
was not working. I changed it toif(_timer !=null)
which did work in my specific code. Thanks for your solution! -
Kasun Hasanga about 2 yearsYes, It is necessary if you use flutter with null safety. !_timer?.isActive means you check _timer Is whether null or not. FYI: dart.dev/null-safety And Also this is not an answer to that question.