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),
            ),
          );
  }
}
相关推荐
布列瑟农的星空4 小时前
Playwright使用体验
前端·单元测试
卤代烃5 小时前
🦾 可为与不可为:CDP 视角下的 Browser 控制边界
前端·人工智能·浏览器
_XU5 小时前
AI工具如何重塑我的开发日常
前端·人工智能·深度学习
C_心欲无痕5 小时前
vue3 - defineExpose暴露给父组件属性和方法
前端·javascript·vue.js·vue3
鹿人戛5 小时前
HarmonyOS应用开发:相机预览花屏问题解决案例
android·前端·harmonyos
萌萌哒草头将军6 小时前
绿联云 NAS 安装 AudioDock 详细教程
前端·docker·容器
贺今宵6 小时前
安装better-sqlite3报错electron-vite
javascript·sql·sqlite·sqlite3
GIS之路6 小时前
GIS 数据转换:使用 GDAL 将 GeoJSON 转换为 Shp 数据
前端
2501_944446006 小时前
Flutter&OpenHarmony文件夹管理功能实现
android·javascript·flutter
朴shu7 小时前
Luckysheet 远程搜索下拉 控件开发 : 揭秘二开全流程
前端