Flutter學習筆記(40)--Timer實現短信驗證碼獲取60s倒計時

如需轉載,請註明出處:Flutter學習筆記(40)--Timer實現短信驗證碼獲取60s倒計時

先看下效果: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';
        }
      })
    });
  }
相關文章
相關標籤/搜索