1.先看看api文檔有沒有像安卓CountDownTimer一樣的類
地址: https://api.dart.dev/stable/2.4.0/dart-async/Timer-class.html

image.png
ok,既然有api,那就照著葫蘆畫瓢
2.導(dǎo)入包
import 'dart:async';
3.添加一個(gè)倒計(jì)時(shí)方法
class LoginPageState extends State<LoginPage> {
//定義變量
Timer _timer;
//倒計(jì)時(shí)數(shù)值
var countdownTime = 0;
//倒計(jì)時(shí)方法
startCountdown() {
countdownTime = 60;
final call = (timer) {
setState(() {
if (countdownTime < 1) {
_timer.cancel();
} else {
countdownTime -= 1;
}
});
};
_timer = Timer.periodic(Duration(seconds: 1), call);
}
咋和官方文檔不一樣,官方的只是倒計(jì)時(shí),而我們需要重復(fù)這個(gè)倒計(jì)時(shí),還是看文檔

image.png
Timer.periodic 為創(chuàng)造一個(gè)重復(fù)的倒計(jì)時(shí)對(duì)象
3.為我們的驗(yàn)證碼 Text添加點(diǎn)擊方法

image.png
可以看到又多了一層判斷countdownTime=0,如果不加這個(gè)判斷的話,每次點(diǎn)擊都會(huì)執(zhí)行開始計(jì)時(shí),計(jì)時(shí)器就會(huì)創(chuàng)建多個(gè)。
4.為Text賦值
我這里定義了一個(gè)方法
String handleCodeText() {
if (countdownTime > 0) {
return "${countdownTime}s后重新獲取";
} else
return "獲取驗(yàn)證碼";
}
當(dāng)然你也可以用Java中的三目運(yùn)算符
child: Text(
countdownTime>0?"${countdownTime}s后重新獲取":"獲取驗(yàn)證碼",
style: TextStyle(
color: Color.fromRGBO(21, 201, 187, 1)),
),
5.別忘了在頁面關(guān)閉時(shí)取消掉這個(gè)Timer
@override
void dispose() {
super.dispose();
if (_timer != null) {
_timer.cancel();
}
}
6.最后來看一下效果吧,為了方便演示,我把時(shí)間調(diào)成了5s

timer.gif