在Flutter中,有一個定時器類Timer,使用方法:
Timer timer = new Timer(new Duration(milliseconds: 60), (){
//倒計時結束執行
});
上面代碼就是執行一個定時器,60秒後執行回調方法。但是無法獲取倒計時的進度。所以我們可以創建一個週期性的Timer:
Timer = countDownTimer = new Timer.periodic(new Duration(seconds: 1), (timer){
print(timer.tick);
});
上面是一個按週期執行的timer,每隔1秒鐘執行一次,所以我們可以利用這個來寫倒計時按鈕。
String yzmText="獲取驗證碼";
new OutlineButton(
onPressed: yzmText=="獲取驗證碼"?yzmGet:null,
padding: EdgeInsets.only(top: 0),
borderSide: new BorderSide(color: mainGreenColor),
highlightedBorderColor: mainGreenColor,
child: new Text(yzmText),
textColor: mainGreenColor,
),
首先定義一個按鈕顯示的文本的變量yzmText,zai onPressed中根據yzmText是否爲"獲取驗證碼"判斷是否可點擊,可點擊的話執行yzmGet方法:
///獲取驗證碼
Timer countDownTimer;
yzmGet() {
countDownTimer?.cancel();//如果已存在先取消置空
countDownTimer = null;
countDownTimer = new Timer.periodic(new Duration(seconds: 1), (t){
setState(() {
if(60-t.tick>0){//60-t.tick代表剩餘秒數,如果大於0,設置yzmText爲剩餘秒數,否則重置yzmText,關閉countTimer
yzmText = "${60-t.tick}秒";
}else{
yzmText = '獲取驗證碼';
countDownTimer.cancel();
countDownTimer = null;
}
});
});
}
最後別忘記在dispose釋放timer:
@override
void dispose() {
// TODO: implement dispose
countDownTimer?.cancel();
countDownTimer = null;
super.dispose();
}
最後的最後:
歡迎各位同學一起學習flutter,羣號:187670882