count_down_button.dart 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:get/get.dart';
  4. import '../utils/index.dart';
  5. typedef CountDownButtonBeforeCheck = bool Function();
  6. class CountDownButton extends StatefulWidget {
  7. final VoidCallback onStartCount; // 开始倒计时后触发 可执行发送短信操作
  8. final CountDownButtonBeforeCheck onCheck; // 开始倒计时前 检查是否要开始 比如验证手机号码
  9. const CountDownButton(this.onCheck, this.onStartCount, {Key? key}) : super(key: key);
  10. @override
  11. State<StatefulWidget> createState() {
  12. return CountDownButtonState();
  13. }
  14. }
  15. class CountDownButtonState extends State<CountDownButton> {
  16. var isCountDown = false;
  17. var _countdownTime = 60; // 60秒倒计时
  18. Timer? _timer; // 计时器
  19. var btnText = 'login_form_code_btn_send'.tr;
  20. @override
  21. Widget build(BuildContext context) {
  22. return ElevatedButton(
  23. onPressed: sendBtnOnTap(),
  24. style: ButtonStyle(
  25. backgroundColor:MaterialStateProperty.resolveWith((states) {
  26. if (states.contains(MaterialState.disabled)) {
  27. return null;
  28. } else {
  29. return Theme.of(context).colorScheme.primary;
  30. }
  31. }),
  32. shape: MaterialStateProperty.all(RoundedRectangleBorder(
  33. borderRadius: BorderRadius.circular(20))), //圆角弧度
  34. ),
  35. autofocus: false,
  36. clipBehavior: Clip.none,
  37. child: Text(btnText, style: const TextStyle(fontSize: 12),));
  38. }
  39. @override
  40. void dispose() {
  41. super.dispose();
  42. _timer?.cancel();
  43. _timer = null;
  44. }
  45. VoidCallback? sendBtnOnTap() {
  46. if (isCountDown) {
  47. return null;
  48. } else {
  49. return () {
  50. OLogger.d('进入点击事件!');
  51. if (!widget.onCheck()) {
  52. OLogger.i("重复点击,不开始倒计时!");
  53. return ;
  54. }
  55. OLogger.d("点击了 倒计时 按钮!");
  56. startCountDown();
  57. // 开始倒计时
  58. setState(() {
  59. isCountDown = true;
  60. _countdownTime = _countdownTime - 1;
  61. btnText = ('$_countdownTime s');
  62. widget.onStartCount();
  63. });
  64. };
  65. }
  66. }
  67. void startCountDown() {
  68. OLogger.i("开始倒计时");
  69. _timer?.cancel();
  70. _timer = null;
  71. const oneSec = Duration(seconds: 1);
  72. _timer = Timer.periodic(oneSec, (timer) => callback());
  73. }
  74. void callback() {
  75. if (_countdownTime < 1) {
  76. _timer?.cancel();
  77. setState(() {
  78. btnText = ('login_form_code_btn_send'.tr);
  79. _countdownTime = 60;
  80. isCountDown = false;
  81. });
  82. } else {
  83. setState(() {
  84. isCountDown = true;
  85. _countdownTime = _countdownTime - 1;
  86. btnText = ('$_countdownTime s');
  87. });
  88. }
  89. }
  90. }