countdown_button_widget.dart 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:lszlgl/base/base_lifecycle_state.dart';
  4. import 'package:lszlgl/config/colors.dart';
  5. import 'package:lszlgl/main.dart';
  6. import 'package:lszlgl/network/my_api.dart';
  7. import 'package:lszlgl/utils/string_utils.dart';
  8. /// 倒计时按钮
  9. class CountdownButtonWidget extends StatefulWidget {
  10. /// 倒计时总秒数
  11. final int timeCount;
  12. /// 手机号
  13. final TextEditingController phoneController;
  14. const CountdownButtonWidget({
  15. Key? key,
  16. this.timeCount = 60,
  17. required this.phoneController,
  18. }) : super(key: key);
  19. @override
  20. State<CountdownButtonWidget> createState() => _CountdownButtonWidgetState();
  21. }
  22. class _CountdownButtonWidgetState extends State<CountdownButtonWidget> {
  23. Timer? _timer;
  24. //倒计时数值
  25. var _countdownTime = 0;
  26. @override
  27. Widget build(BuildContext context) {
  28. return GestureDetector(
  29. child: Text(
  30. _handleBtnText(),
  31. style: const TextStyle(
  32. color: MyColor.c_25A6EE, fontSize: 14),
  33. ),
  34. onTap: () async{
  35. if (_countdownTime == 0) {
  36. if (!StringUtils.isPhoneNum(widget.phoneController.text)) {
  37. MyNavigator.showToast('请输入正确的手机号');
  38. return;
  39. }
  40. bool isPost = await getPhoneMsg();
  41. if(!isPost){
  42. return;
  43. }
  44. // print('可以发送了');
  45. _startCountdown();
  46. }
  47. },
  48. );
  49. }
  50. /// 获取验证码
  51. Future<bool> getPhoneMsg() async{
  52. try{
  53. var res = await MyApi.get().postPhoneMsg({
  54. 'mobile': widget.phoneController.text,
  55. 'scene': 23,
  56. });
  57. //print('$res.data');
  58. if( res.data ?? false){
  59. MyNavigator.showToast('验证码已发送');
  60. return true;
  61. }else{
  62. return false;
  63. }
  64. }catch(e){
  65. logger.e(e);
  66. return false;
  67. }
  68. }
  69. String _handleBtnText() {
  70. if (_countdownTime > 0) {
  71. return '剩余$_countdownTime秒';
  72. } else {
  73. return '获取验证码';
  74. }
  75. }
  76. //倒计时方法
  77. void _startCountdown() {
  78. //倒计时时间
  79. _countdownTime = widget.timeCount;
  80. if (_timer != null) {
  81. // 如果timer已存在要先取消置空
  82. _timer!.cancel();
  83. _timer = null;
  84. }
  85. _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
  86. if (_countdownTime < 1) {
  87. _timer?.cancel();
  88. } else {
  89. setState(() {
  90. _countdownTime -= 1;
  91. });
  92. }
  93. });
  94. }
  95. @override
  96. void dispose() {
  97. _timer?.cancel();
  98. _timer = null;
  99. super.dispose();
  100. }
  101. }