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),
            ),
          );
  }
}
相关推荐
paopaokaka_luck1 小时前
基于SpringBoot+Uniapp的健身饮食小程序(协同过滤算法、地图组件)
前端·javascript·vue.js·spring boot·后端·小程序·uni-app
患得患失9492 小时前
【前端】【vscode】【.vscode/settings.json】为单个项目配置自动格式化和开发环境
前端·vscode·json
飛_2 小时前
解决VSCode无法加载Json架构问题
java·服务器·前端
YGY Webgis糕手之路4 小时前
OpenLayers 综合案例-轨迹回放
前端·经验分享·笔记·vue·web
90后的晨仔5 小时前
🚨XSS 攻击全解:什么是跨站脚本攻击?前端如何防御?
前端·vue.js
Ares-Wang5 小时前
JavaScript》》JS》 Var、Let、Const 大总结
开发语言·前端·javascript
90后的晨仔5 小时前
Vue 模板语法完全指南:从插值表达式到动态指令,彻底搞懂 Vue 模板语言
前端·vue.js
德育处主任5 小时前
p5.js 正方形square的基础用法
前端·数据可视化·canvas
烛阴5 小时前
Mix - Bilinear Interpolation
前端·webgl
90后的晨仔5 小时前
Vue 3 应用实例详解:从 createApp 到 mount,你真正掌握了吗?
前端·vue.js