Flutter获取验证码倒计时按钮

在Flutter中,有一个定时器类Timer,使用方法:

Timer timer = new Timer(new Duration(milliseconds: 60), (){
        //倒计时结束执行
      });

上面代码就是执行一个定时器,60秒后执行回调方法。但是无法获取倒计时的进度。所以我们可以创建一个周期性的Timer:

Timer = countDownTimer = new Timer.periodic(new Duration(seconds: 1), (timer){
        print(timer.tick);
      });

上面是一个按周期执行的timer,每隔1秒钟执行一次,所以我们可以利用这个来写倒计时按钮。

				String yzmText="获取验证码";
                  new OutlineButton(
                    onPressed: yzmText=="获取验证码"?yzmGet:null,
                    padding: EdgeInsets.only(top: 0),
                    borderSide: new BorderSide(color: mainGreenColor),
                    highlightedBorderColor: mainGreenColor,
                    child: new Text(yzmText),
                    textColor: mainGreenColor,
                  ),

首先定义一个按钮显示的文本的变量yzmText,zai onPressed中根据yzmText是否为"获取验证码"判断是否可点击,可点击的话执行yzmGet方法:

	///获取验证码
  Timer countDownTimer;
  yzmGet() {
    countDownTimer?.cancel();//如果已存在先取消置空
    countDownTimer = null;
      countDownTimer = new Timer.periodic(new Duration(seconds: 1), (t){
        setState(() {
          if(60-t.tick>0){//60-t.tick代表剩余秒数,如果大于0,设置yzmText为剩余秒数,否则重置yzmText,关闭countTimer
            yzmText = "${60-t.tick}秒";
          }else{
            yzmText = '获取验证码';
            countDownTimer.cancel();
            countDownTimer = null;
          }
        });
      });
  }

最后别忘记在dispose释放timer:

@override
    void dispose() {
    // TODO: implement dispose
    countDownTimer?.cancel();
    countDownTimer = null;
    super.dispose();

  }

最后的最后:

欢迎各位同学一起学习flutter,群号:187670882
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章