【发布时间】:2020-05-29 04:05:52
【问题描述】:
我在另一个线程上遇到了这段用于计时器的代码。当您同时按下RaisedButton 多次时,它会为每次点击增加-1 秒,从而增加减少率。
关于检查计时器是否已激活以及是否不让RaisedButton 创建新计时器的最简单方法的任何想法。谢谢!
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")
],
),
);
}
【问题讨论】: