源代碼是參考https://www.jianshu.com/p/e941fe68694c文章的,但是再運作的時候,隻有第一次點選有效,再次點選就不執行倒計時了。
上效果圖

上代碼,大家可以直接複制用的
//發送驗證碼倒計時子產品
import 'dart:async';
import '../config/index.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class VercodeTimerWidget extends StatefulWidget {
@override
_VercodeTimerWidgetState createState() => _VercodeTimerWidgetState();
}
class _VercodeTimerWidgetState extends State<VercodeTimerWidget> {
Timer _timer;
//倒計時數值
var _countdownTime = 0;
@override
Widget build(BuildContext context) {
return FlatButton(
disabledColor:HspColor.btn_disabledColor,
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
hoverColor: Colors.transparent,
color: HspColor.btn_oringe,
padding: EdgeInsets.only(right: 0),
child: Text(handleCodeAutoSizeText(),
style: TextStyle(
color: Colors.white,
)),
onPressed:_countdownTime==0?btnPress():null,
);
}
btnPress(){
if(_countdownTime==0) {
return () {
startCountdown();
};
}
}
String handleCodeAutoSizeText() {
if (_countdownTime > 0) {
return '$_countdownTime'+'s後重新發送';
} else
return '擷取驗證碼';
}
call (timer) {
if (_countdownTime < 1) {
print("定時器取消了");
_timer.cancel();
_timer=null;/原部落客的代碼少了這個
} else {
setState(() {
_countdownTime -= 1;
});
}
print(_countdownTime);
}
//倒計時方法
startCountdown() {
print("我竟來了");
//倒計時時間
_countdownTime = 60;
print({
_countdownTime:_countdownTime,
_timer:_timer == null
});
print(_timer);
if (_timer == null) {/是以第一次循環是_timer是null,再次點選時_timer == null為false
print("開啟定時器");
_timer = Timer.periodic(Duration(seconds: 1), call);
//原因是_timer被指派了,是以在清除定時器後我手動指派null
}
}
@override
void dispose() {
super.dispose();
if (_timer != null) {
print("銷毀啦");
_timer.cancel();
}
}
}