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),
            ),
          );
  }
}
相关推荐
zwjapple3 小时前
docker-compose一键部署全栈项目。springboot后端,react前端
前端·spring boot·docker
像风一样自由20205 小时前
HTML与JavaScript:构建动态交互式Web页面的基石
前端·javascript·html
哲科软件6 小时前
跨平台开发的抉择:Flutter vs 原生安卓(Kotlin)的优劣对比与选型建议
android·flutter·kotlin
天涯海风6 小时前
Kuikly 与 Flutter 的全面对比分析,结合技术架构、性能、开发体验等核心维度
flutter·kuikly
aiprtem6 小时前
基于Flutter的web登录设计
前端·flutter
浪裡遊6 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
why技术6 小时前
Stack Overflow,轰然倒下!
前端·人工智能·后端
GISer_Jing6 小时前
0704-0706上海,又聚上了
前端·新浪微博
止观止6 小时前
深入探索 pnpm:高效磁盘利用与灵活的包管理解决方案
前端·pnpm·前端工程化·包管理器
whale fall6 小时前
npm install安装的node_modules是什么
前端·npm·node.js