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),
            ),
          );
  }
}
相关推荐
学习星球1 小时前
Solid.js 实战:拆解官方 RealWorld 项目
开发语言·javascript·vue.js
风骏时光牛马2 小时前
AIAgent高可用架构:弹性容错与故障自愈的落地实践
前端
IT_陈寒2 小时前
Vue的响应式什么时候会失灵?这个坑我踩了
前端·人工智能·后端
烟锁池塘柳02 小时前
解决 Firefox 浏览器网页文本选中高亮不明显问题(含仅修改特定网站高亮显示的方案)
前端·firefox
Patrick_Wilson2 小时前
Web 认证方案技术指南
前端·后端·面试
YuJie3 小时前
JSBridge 基础知识
前端·javascript
BigTopOne3 小时前
Ubuntu 虚拟机编译 WebRTC Android AAR(M140 / branch-heads/7339)
前端
默_笙3 小时前
🍕 后端接口还没写好,前端已经跑起来了?Mock 数据 + axios 接口层,前后端再也不互相"等"
前端·javascript
书源3 小时前
AI 时代写给前端同行:什么在贬值,什么在涨价
前端·程序员·ai编程
爱勇宝3 小时前
客户只想看个页面,我却做了一个静态演示发布系统
前端·javascript·后端