flutter 获取验证码倒计时组件封装

send_sms_btn.dart

Dart 复制代码
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';

// 发送验证码 按钮
class SendSmsBtn extends StatefulWidget {
  final Future<bool> Function()? onTap;
  const SendSmsBtn({
    super.key,
    this.onTap,
  });

  @override
  State<SendSmsBtn> createState() => _SendSmsBtnState();
}

class _SendSmsBtnState extends State<SendSmsBtn> {
  int countdown = 60;
  Timer? timer;

  void sendRegisterMsgCode() {
    if (countdown == 60) {
      countdown--;
      setState(() {});
      timer?.cancel();
      timer = null;
      timer ??= Timer.periodic(const Duration(seconds: 1), (timer) {
        countdown--;
        if (countdown == 0) {
          timer.cancel();
          countdown = 60;
        }
        setState(() {});
      });
    }
  }

  @override
  void dispose() {
    timer?.cancel();
    timer = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return countdown == 60
        ? InkWell(
            onTap: () async {
              //  AppToast.showLoading();
              final s = await widget.onTap?.call() ?? false;
              // AppToast.closeAllLoading();
              if (s) {
                sendRegisterMsgCode();
              }
            },
            child: Container(
              width: 123,
              height: 43,
              alignment: Alignment.centerRight,
              child: Text(
                "发送验证码",
                style: TextStyle(color: Get.theme.primaryColor, fontSize: 14),
              ),
            ),
          )
        : Container(
            width: 123,
            height: 43,
            alignment: Alignment.centerRight,
            child: Text(
              "$countdown s重新获取",
              style: TextStyle(color: Get.theme.primaryColor, fontSize: 14),
            ),
          );
  }
}
相关推荐
TE-茶叶蛋6 分钟前
Uniapp、Flutter 和 React Native 全面对比
flutter·react native·uni-app
yyywoaini~13 分钟前
wordcount程序
前端·javascript·ajax
Yvonne爱编码24 分钟前
CSS- 4.2 相对定位(position: relative)
前端·css·状态模式·html5·hbuilder
白小白灬33 分钟前
Vue主题色切换实现方案(CSS 变量 + 类名切换)
前端·css·vue.js
江沉晚呤时38 分钟前
.NET Core 中 Swagger 配置详解:常用配置与实战技巧
前端·.netcore
waterHBO1 小时前
chrome 浏览器插件 myTools, 日常小工具。
前端·chrome
哎呦你好1 小时前
HTML 颜色全解析:从命名规则到 RGBA/HSL 值,附透明度设置与场景应用指南
前端·css·html
多云的夏天1 小时前
前端:VUE-(0)-环境搭建和helloworld
前端·javascript·vue.js
Dontla1 小时前
BootCDN介绍(Bootstrap主导的前端开源项目免费CDN加速服务)
前端·开源·bootstrap
开开心心就好2 小时前
Word图片格式调整与转换工具
java·javascript·spring·eclipse·pdf·word·excel