我一直在学习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")
],
),
);
}
[使用_timer
的isActive
属性添加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;
}
},
),
);
}
}