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),
            ),
          );
  }
}
相关推荐
L、2181 小时前
Flutter 与 OpenHarmony 深度集成:构建分布式多端协同应用
分布式·flutter·wpf
小a杰.1 小时前
Flutter 开发工具链详解
flutter
qq_381454991 小时前
设计模式详解:代码架构的艺术
开发语言·javascript·ecmascript
半桶水专家1 小时前
vue3中v-model 用法详解
前端·javascript·vue.js
行走的陀螺仪1 小时前
Vue3 项目单元测试全指南:价值、Vitest 落地与提效方案
开发语言·前端·单元测试·html5·vitest
AI浩9 小时前
【Labelme数据操作】LabelMe标注批量复制工具 - 完整教程
运维·服务器·前端
扶我起来还能学_9 小时前
Flutter 轮播图封装
flutter
涔溪9 小时前
CSS 网格布局(Grid Layout)核心概念、基础语法、常用属性、实战示例和进阶技巧全面讲解
前端·css
2401_878454539 小时前
浏览器工作原理
前端·javascript
西陵10 小时前
为什么说 AI 赋能前端开发,已经不是选择题,而是必然趋势?
前端·架构·ai编程