flutter开发之验证码倒计时

源代码是参考https://www.jianshu.com/p/e941fe68694c文章的,但是再运行的时候,只有第一次点击有效,再次点击就不执行倒计时了。

上效果图

在这里插入图片描述

上代码,大家可以直接复制用的

//发送验证码倒计时模块
import 'dart:async';
import '../config/index.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';


class VercodeTimerWidget extends StatefulWidget {
  @override
  _VercodeTimerWidgetState createState() => _VercodeTimerWidgetState();
}

class _VercodeTimerWidgetState extends State<VercodeTimerWidget> {
  Timer _timer;

  //倒计时数值
  var _countdownTime = 0;
  @override
  Widget build(BuildContext context) {
    return FlatButton(
      disabledColor:HspColor.btn_disabledColor,
      splashColor: Colors.transparent,
      highlightColor: Colors.transparent,
      hoverColor: Colors.transparent,
      color: HspColor.btn_oringe,
      padding: EdgeInsets.only(right: 0),
      child: Text(handleCodeAutoSizeText(),
          style: TextStyle(
              color: Colors.white,
              )),
      onPressed:_countdownTime==0?btnPress():null,
    );
  }

   btnPress(){
    if(_countdownTime==0) {
      return () {
        startCountdown();
      };
    }
  }

  String handleCodeAutoSizeText() {
    if (_countdownTime > 0) {
      return '$_countdownTime'+'s后重新发送';
    } else
      return '获取验证码';
  }

  call (timer) {
    if (_countdownTime < 1) {
      print("定时器取消了");
      _timer.cancel();
      _timer=null;/原博主的代码少了这个
    } else {
      setState(() {
        _countdownTime -= 1;
      });
    }
    print(_countdownTime);
  }

  //倒计时方法
  startCountdown() {
    print("我竟来了");
    //倒计时时间
    _countdownTime = 60;
    print({
      _countdownTime:_countdownTime,
      _timer:_timer == null
    });
    print(_timer);
    if (_timer == null) {/所以第一次循环是_timer是null,再次点击时_timer == null为false
      print("开启定时器");
      _timer = Timer.periodic(Duration(seconds: 1), call);
      //原因是_timer被赋值了,所以在清除定时器后我手动赋值null
    }


  }

  @override
  void dispose() {
    super.dispose();
    if (_timer != null) {
      print("销毁啦");
      _timer.cancel();
    }
  }
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

华山派developer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值