先看下效果:html
两种需求场景:post
1.广告页3s后跳转到首页学习
2.短信验证码60s倒计时url
第一种的话,根据需求咱们能够知道,咱们想要的效果就是3s结束作出一个动做。spa
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回调方法,即超时后你想要执行的动做是什么,好比跳转到首页。code
第二种的话就是须要不断的作出倒计时的动做。htm
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倒计时获取。blog
看下具体用法吧:事件
Timer _timer; int _timeCount = 60;
触发事件:ip
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'; } }) }); }