如需轉載,請註明出處:Flutter學習筆記(40)--Timer實現簡訊驗證碼獲取60s倒計時 先看下效果: 兩種需求場景: 1.廣告頁3s後跳轉到首頁 2.簡訊驗證碼60s倒計時 第一種的話,根據需求我們可以知道,我們想要的效果就是3s結束做出一個動作。 factory Timer(Durati ...
如需轉載,請註明出處: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'; } }) }); }