3

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
  • 92
  • 1
  • 10

2 Answers2

5

Add a check to see if _timer is already active using the isActive property of Timers. 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;
          }
        },
      ),
    );
  }
}
Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
  • 2
    I 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 to `if(_timer !=null)` which did work in my specific code. Thanks for your solution! – Andrew Caprario May 29 '20 at 23:06
-1

The receiver can't be null, so the null-aware operator '?.' is unnecessary. Change this:

if(!_timer?.isActive)

to

if(!_timer.isActive)

jrana
  • 16
  • 4
  • Yes, It is necessary if you use flutter with null safety. !_timer?.isActive means you check _timer Is whether null or not. FYI: https://dart.dev/null-safety And Also this is not an answer to that question. – Kasun Hasanga Mar 27 '22 at 17:19