startTimer()仅在当前不活动时被激活

问题描述 投票:0回答:1

我一直在学习Dart / Flutter,却在另一个线程上偶然发现了这个计时器代码。我一直在玩它,并注意到它的当前编写方式,当您按下RaisedButton时,每次单击都会增加-1秒,从而增加了降低率。我对如何设置此计时器以仅在startTimer当前未递减计数时激活_timer感到困惑。谢谢!

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")
      ],
    ),
  );
}
flutter dart timer
1个回答
0
投票

[使用_timerisActive属性添加Timer是否已经激活的检查。如果它已经处于活动状态,则不会创建新的。

示例:

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;
          }
        },
      ),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.