我在另一个线程上遇到了这个计时器代码。当您按下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")
],
),
);
}
添加检查以查看是否_timer
已经使用isActive
的财产Timer
s。如果它已经处于活动状态,则不会创建新的。
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;
}
},
),
);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)