如何解决计时器的值倒计时不会立即波动
我正在使用timer_count_down软件包。 (https://pub.dev/packages/timer_count_down),当我以新值(计时器秒)重新启动计时器时。计时器以旧值开始,而不是新值。简而言之,我的状态不会立即更新。并且计时器以旧值重新启动。请帮助我。
Widget build(BuildContext context) {
return Countdown(
controller: contrl,//controller for timer
seconds: time,//time is a state which store seconds.
build: (BuildContext context,double time) => Text(time.toString()),interval: Duration(milliseconds: 100),onFinished: () {
time = 30;//new time updated for timer
contrl.restart();// this will restart mytimer// but timer is not taking new value it restarts with old value//
},);
} }
解决方法
似乎该软件包并非设计用于这种方式(onFinished->重新启动)。这不是一个干净的解决方法,但是您可以尝试以下
Countdown(
controller: contrl,//controller for timer
seconds: time,//time is a state which store seconds.
build: (BuildContext context,double time) => Text(time.toString()),interval: Duration(milliseconds: 100),onFinished: () {
//new time updated for timer
setState(() {
time = 10;
});
Future.delayed(Duration(seconds: 1)).then((value) {
contrl.restart();
});
// this will restart mytimer// but timer is not taking new value it restarts with old value//
},),
或者像这样实现自己的倒数逻辑:
class NewPage extends StatefulWidget {
@override
_NewPageState createState() => _NewPageState();
}
class _NewPageState extends State<NewPage> {
Duration time = Duration(seconds: 3);
Timer _timer;
void startTimer(Duration reStartTime,Duration interval) {
_timer = Timer.periodic(interval,(Timer t) {
if (time <= Duration()) {
setState(() {
time = reStartTime;
});
} else {
setState(() {
time -= interval;
});
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
startTimer(Duration(seconds: 30),Duration(milliseconds: 100));
},appBar: AppBar(
title: Text('Second Page'),body: Center(child: Text('$time')),);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。