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),
            ),
          );
  }
}
相关推荐
以明志、19 小时前
并行与并发
前端·数据库·c#
提笔了无痕19 小时前
go web开发表单知识及表单处理详解
前端·后端·golang·web
甜味弥漫20 小时前
JavaScript新手必看系列之预编译
前端·javascript
小哀220 小时前
🌸 入职写了一个月全栈next.js 感想
前端·后端·ai编程
用户0102692718620 小时前
swift的inout的用法
前端
用户66006766853920 小时前
搞懂作用域链与闭包:JS底层逻辑变简单
前端·javascript
yinuo20 小时前
前端跨页面通讯终极指南②:BroadcastChannel 用法全解析
前端
没落英雄20 小时前
简单了解 with
前端·javascript
越努力越幸运50820 小时前
webpack的学习打包工具
前端·学习·webpack
IT古董20 小时前
微前端的新纪元:Vite + Module Federation 最强指南(2025 全面技术解析)
前端