Flutter学习笔记(40)--Timer实现短信验证码获取60s倒计时
如需转载,请注明出处:Flutter学习笔记(40)--Timer实现短信验证码获取60s倒计时
先看下效果:
两种需求场景:
1.广告页3s后跳转到首页
2.短信验证码60s倒计时
第一种的话,根据需求我们可以知道,我们想要的效果就是3s结束做出一个动作。
factory Timer(Duration duration, void callback()) { if (Zone.current == Zone.root) { // No need to bind the callback. We know that the root's timer will // be invoked in the root zone. return Zone.current.createTimer(duration, callback); } return Zone.current .createTimer(duration, Zone.current.bindCallbackGuarded(callback)); }
两个参数,第一个参数超时时间,即多久后执行你想要的动作,第二个参数callback回调方法,即超时后你想要执行的动作是什么,比如跳转到首页。
第二种的话就是需要不断的做出倒计时的动作。
factory Timer.periodic(Duration duration, void callback(Timer timer)) { if (Zone.current == Zone.root) { // No need to bind the callback. We know that the root's timer will // be invoked in the root zone. return Zone.current.createPeriodicTimer(duration, callback); } var boundCallback = Zone.current.bindUnaryCallbackGuarded<Timer>(callback); return Zone.current.createPeriodicTimer(duration, boundCallback); }
这种调用方式和上面的方式的区别是:第一种只会回调一次,就是超时时间到了之后执行callback回调方法,而Timer.periodic调用方式是循环不断的调用,比如说通过这种方式,你设置的超时时间是1s的话,那就会每隔1s调用一次callback的回调方法,也就是通过这种方式来实现我们的短信验证码60s倒计时获取。
看下具体用法吧:
Timer _timer; int _timeCount = 60;
触发事件:
onTap: () {
_startTimer();
},
处理方法:
void _startTimer() { ToastUtil.showTips('短信验证码已发送,请注意查收'); _timer = Timer.periodic(Duration(seconds: 1), (Timer timer) => { setState(() { if(_timeCount <= 0){ _autoCodeText = '重新获取'; _timer.cancel(); _timeCount = 60; }else { _timeCount -= 1; _autoCodeText = "$_timeCount" + 's'; } }) }); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效