Flutter:驗(yàn)證碼倒計(jì)時(shí)的實(shí)現(xiàn)

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

github:https://github.com/Lans/flutter_timer

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容