我有一个倒数计时器(5 分钟)。我需要一些东西来重新开始这个倒计时并从头开始。
我尝试更改倒计时变量的状态但不起作用,停止并从计数器的最后一个数字重新启动。
我的代码:
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:quiver/async.dart';
class ProgressIndicatorDemo extends StatefulWidget {
@override
_ProgressIndicatorDemoState createState() =>
new _ProgressIndicatorDemoState();
}
class _ProgressIndicatorDemoState extends State<ProgressIndicatorDemo>
with SingleTickerProviderStateMixin {
AnimationController controller;
Animation<double> animation;
var countdown;
int actual;
@override
void initState() {
super.initState();
animationStart();
startTimer();
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
void animationStart() {
controller =
AnimationController(duration: Duration(minutes: 5), vsync: this);
animation = Tween(begin: 0.0, end: 1.0).animate(controller)
..addListener(() {
setState(() {});
});
controller.forward();
}
void startTimer() {
CountdownTimer countDownTimer = new CountdownTimer(
new Duration(minutes: 5),
new Duration(seconds: 1),
);
countdown = countDownTimer.listen(null);
countdown.onData((duration) {
setState(() {
actual = 300 - duration.elapsed.inSeconds;
});
});
countdown.onDone(() {
countdown.cancel();
});
}
@override
Widget build(BuildContext context) {
return new Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
animation.value != 1.0
? CircularProgressIndicator(
semanticsLabel:
(animation.value * 100.0).toStringAsFixed(1).toString() +
'%',
semanticsValue:
(animation.value * 100.0).toStringAsFixed(1).toString() +
'%',
backgroundColor: Colors.black.withOpacity(0.25),
valueColor:
new AlwaysStoppedAnimation<Color>(Colors.green[700]),
value: animation.value)
: Icon(Icons.info_outline),
actual != null
? Text(
"Tiempo:" +
DateFormat.ms()
.format(DateTime.fromMillisecondsSinceEpoch(
actual * 1000))
.toString(),
textAlign: TextAlign.center,
)
: Container(),
FlatButton(
child: Text('Reset ' + actual.toString()), onPressed: () {}),
],
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
所以问题是:我怎样才能从开始倒计时重新开始?
die*_*per 11
尝试先取消计时器并再次启动计时器:
void restartTimer() {
countDownTimer.cancel();
startTimer();
}
Run Code Online (Sandbox Code Playgroud)
小智 7
您可以使用更清洁的解决方案 RestartableTimer
import 'package:async/async.dart';
RestartableTimer _timer = new RestartableTimer(_timerDuration, _startNewPage);
Run Code Online (Sandbox Code Playgroud)
然后您可以通过简单地调用重新开始倒计时 _timer.reset();
希望能帮助到你。
| 归档时间: |
|
| 查看次数: |
3957 次 |
| 最近记录: |