颤动倒数计时器 [英] Flutter Countdown Timer

查看:78
本文介绍了颤动倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何将传递的值放入构造中,以使计时器四舍五入到小数点后第一位并显示在RaisedButton的子文本中?我尝试过但没有运气。我设法用一个简单的Timer来使回调函数起作用,但是没有周期性,并且文本中没有实时的值更新...

  import'package:flutter / material.dart'; 
导入 dart:ui;
导入 dart:async;

类TimerButton扩展了StatefulWidget {
final Duration timerTastoPremuto;


TimerButton(this.timerTastoPremuto);

@override
_TimerButtonState createState()=> _TimerButtonState();
}

类_TimerButtonState扩展了State< TimerButton> {
@override
Widget build(BuildContext context){
return Container(
margin:EdgeInsets.all(5.0),
height:135.0,
宽度:135.0,
子级:new RaisedButton(
高程:100.0,
颜色:Colors.white.withOpacity(.8),
高亮高度:0.0,
onPressed :(){
int _start = widget.timerTastoPremuto.inMilliseconds;

const oneDecimal = const Duration(毫秒:100);
Timer _timer = new Timer.periodic(
oneDecimal,
(Timer timer)=>
setState((){
if(_start< 100){
_timer.cancel();
} else {
_start = _start-100;
}
}));

},
splashColor:Colors.red,
HighlightColor:Colors.red ,
//形状:RoundedRectangleBorder和其他形状
形状:BeveledRectangleBorder(
侧面:BorderSide(color:Colors.black,width:2.5),
borderRadius:new BorderRadius .circular(15.0)),
子项:new Text(
$ _start,
样式:new TextStyle(fontFamily: Minim,fontSize:50.0),
) ,
),
);
}
}


解决方案

此处是使用



您还可以使用 CountdownTimer 类,来自 quiver.async 库,用法甚至更简单:

  import'package: quiver / async.dart'; 

[...]

int _start = 10;
int _current = 10;

void startTimer(){
CountdownTimer countDownTimer = new CountdownTimer(
new Duration(seconds _start),
new Duration(seconds:1),
);

var sub = countDownTimer.listen(null);
sub.onData((duration){
setState((){_current = _start-duration.elapsed.inSeconds;});
});

sub.onDone((){
print( Done);
sub.cancel();
});
}

窗口小部件build(BuildContext context){
返回新的Scaffold(
appBar:AppBar(title:Text( Timer test))),
正文:列(
子项:< Widget> [
RaisedButton(
onPressed:(){
startTimer();
},
子项:Text( start),
),
Text( $ _ current)
],
),
);
}






编辑:有关按钮单击行为的注释中的问题



使用上面的代码使用 Timer.periodic ,则确实会在每次按钮单击时启动一个新计时器,所有这些计时器都将更新相同的 _start 变量,从而使计数器减少的速度更快。



有多种解决方案可以更改此行为,具体取决于您要实现的目标:




  • 禁用单击一次按钮,以便用户不再打扰倒计时(也许在取消计时器后可以重新启用倒计时)

  • 包装 Timer.periodic 使用非null条件创建,因此多次单击按钮无效



  if(_timer!= null){
_timer = new Timer.periodic(...);
}




  • 取消计时器并重置倒计时想要在每次单击时重新启动计时器:



  if( _timer!= null){
_timer.cancel();
_start = 10;
}
_timer = new Timer.periodic(...);




  • 如果您希望按钮像播放/暂停按钮那样起作用:



  if(_timer!= null){
_timer.cancel();
_timer = null;
} else {
_timer = new Timer.periodic(...);
}

您也可以使用此官方 async 软件包,其中提供了 RestartableTimer 类,它从 Timer 扩展并添加了 reset 方法。



因此,每次单击按钮只需调用 _timer.reset();



最后,Codepen现在支持Flutter!因此,这是一个实时示例,每个人都可以使用它: https://codepen.io/Yann39/pen / oNjrVOb


How can I do to put the value passed in the construction, to make a timer that rounds to the first decimal and shows at the child text of my RaisedButton? I've tried but without luck. I manage to make work the callback function with a simple Timer but no periodic and with no update of value in real time in the text...

import 'package:flutter/material.dart';
import 'dart:ui';
import 'dart:async';

class TimerButton extends StatefulWidget {
  final Duration timerTastoPremuto;


  TimerButton(this.timerTastoPremuto);

  @override
  _TimerButtonState createState() => _TimerButtonState();
}

class _TimerButtonState extends State<TimerButton> {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(5.0),
      height: 135.0,
      width: 135.0,
      child: new RaisedButton(
        elevation: 100.0,
        color: Colors.white.withOpacity(.8),
        highlightElevation: 0.0,
        onPressed: () {
          int _start = widget.timerTastoPremuto.inMilliseconds;

          const oneDecimal = const Duration(milliseconds: 100);
          Timer _timer = new Timer.periodic(
              oneDecimal,
                  (Timer timer) =>
                  setState(() {
                    if (_start < 100) {
                      _timer.cancel();
                    } else {
                      _start = _start - 100;
                    }
                  }));

        },
        splashColor: Colors.red,
        highlightColor: Colors.red,
        //shape: RoundedRectangleBorder e tutto il resto uguale
        shape: BeveledRectangleBorder(
            side: BorderSide(color: Colors.black, width: 2.5),
            borderRadius: new BorderRadius.circular(15.0)),
        child: new Text(
          "$_start",
          style: new TextStyle(fontFamily: "Minim", fontSize: 50.0),
        ),
      ),
    );
  }
}

解决方案

Here is an example using Timer.periodic :

Countdown starts from 10 to 0 on button click :

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")
      ],
    ),
  );
}

Result :

You can also use the CountdownTimer class from the quiver.async library, usage is even simpler :

import 'package:quiver/async.dart';

[...]

int _start = 10;
int _current = 10;

void startTimer() {
  CountdownTimer countDownTimer = new CountdownTimer(
    new Duration(seconds: _start),
    new Duration(seconds: 1),
  );

  var sub = countDownTimer.listen(null);
  sub.onData((duration) {
    setState(() { _current = _start - duration.elapsed.inSeconds; });
  });

  sub.onDone(() {
    print("Done");
    sub.cancel();
  });
}

Widget build(BuildContext context) {
  return new Scaffold(
    appBar: AppBar(title: Text("Timer test")),
    body: Column(
      children: <Widget>[
        RaisedButton(
          onPressed: () {
            startTimer();
          },
          child: Text("start"),
        ),
        Text("$_current")
      ],
    ),
  );
}


EDIT : For the question in comments about button click behavior

With the above code which uses Timer.periodic, a new timer will indeed be started on each button click, and all these timers will update the same _start variable, resulting in a faster decreasing counter.

There are multiple solutions to change this behavior, depending on what you want to achieve :

  • disable the button once clicked so that the user could not disturb the countdown anymore (maybe enable it back once timer is cancelled)
  • wrap the Timer.periodic creation with a non null condition so that clicking the button multiple times has no effect

if (_timer != null) {
  _timer = new Timer.periodic(...);
}

  • cancel the timer and reset the countdown if you want to restart the timer on each click :

if (_timer != null) {
  _timer.cancel();
  _start = 10;
}
_timer = new Timer.periodic(...);

  • if you want the button to act like a play/pause button :

if (_timer != null) {
  _timer.cancel();
  _timer = null;
} else {
  _timer = new Timer.periodic(...);
}

You could also use this official async package which provides a RestartableTimer class which extends from Timer and adds the reset method.

So just call _timer.reset(); on each button click.

Finally, Codepen now supports Flutter ! So here is a live example so that everyone can play with it : https://codepen.io/Yann39/pen/oNjrVOb

这篇关于颤动倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆