123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- import 'dart:async';
- import 'package:flutter/material.dart';
- import 'package:get/get.dart';
- import '../utils/index.dart';
- typedef CountDownButtonBeforeCheck = bool Function();
- class CountDownButton extends StatefulWidget {
- final VoidCallback onStartCount; // 开始倒计时后触发 可执行发送短信操作
- final CountDownButtonBeforeCheck onCheck; // 开始倒计时前 检查是否要开始 比如验证手机号码
- const CountDownButton(this.onCheck, this.onStartCount, {Key? key}) : super(key: key);
- @override
- State<StatefulWidget> createState() {
- return CountDownButtonState();
- }
- }
- class CountDownButtonState extends State<CountDownButton> {
- var isCountDown = false;
- var _countdownTime = 60; // 60秒倒计时
- Timer? _timer; // 计时器
- var btnText = 'login_form_code_btn_send'.tr;
- @override
- Widget build(BuildContext context) {
- return ElevatedButton(
- onPressed: sendBtnOnTap(),
- style: ButtonStyle(
- backgroundColor:MaterialStateProperty.resolveWith((states) {
- if (states.contains(MaterialState.disabled)) {
- return null;
- } else {
- return Theme.of(context).colorScheme.primary;
- }
- }),
- shape: MaterialStateProperty.all(RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(20))), //圆角弧度
- ),
- autofocus: false,
- clipBehavior: Clip.none,
- child: Text(btnText, style: const TextStyle(fontSize: 12),));
- }
- @override
- void dispose() {
- super.dispose();
- _timer?.cancel();
- _timer = null;
- }
-
- VoidCallback? sendBtnOnTap() {
- if (isCountDown) {
- return null;
- } else {
- return () {
- OLogger.d('进入点击事件!');
- if (!widget.onCheck()) {
- OLogger.i("重复点击,不开始倒计时!");
- return ;
- }
- OLogger.d("点击了 倒计时 按钮!");
- startCountDown();
- // 开始倒计时
- setState(() {
- isCountDown = true;
- _countdownTime = _countdownTime - 1;
- btnText = ('$_countdownTime s');
- widget.onStartCount();
- });
- };
- }
- }
- void startCountDown() {
- OLogger.i("开始倒计时");
- _timer?.cancel();
- _timer = null;
- const oneSec = Duration(seconds: 1);
- _timer = Timer.periodic(oneSec, (timer) => callback());
- }
- void callback() {
- if (_countdownTime < 1) {
- _timer?.cancel();
- setState(() {
- btnText = ('login_form_code_btn_send'.tr);
- _countdownTime = 60;
- isCountDown = false;
- });
- } else {
- setState(() {
- isCountDown = true;
- _countdownTime = _countdownTime - 1;
- btnText = ('$_countdownTime s');
- });
- }
- }
- }
-
|