123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- import 'dart:async';
- import 'package:flutter/material.dart';
- import 'package:lszlgl/base/base_lifecycle_state.dart';
- import 'package:lszlgl/config/colors.dart';
- import 'package:lszlgl/main.dart';
- import 'package:lszlgl/network/my_api.dart';
- import 'package:lszlgl/utils/string_utils.dart';
- /// 倒计时按钮
- class CountdownButtonWidget extends StatefulWidget {
- /// 倒计时总秒数
- final int timeCount;
- /// 手机号
- final TextEditingController phoneController;
- const CountdownButtonWidget({
- Key? key,
- this.timeCount = 60,
- required this.phoneController,
- }) : super(key: key);
- @override
- State<CountdownButtonWidget> createState() => _CountdownButtonWidgetState();
- }
- class _CountdownButtonWidgetState extends State<CountdownButtonWidget> {
- Timer? _timer;
- //倒计时数值
- var _countdownTime = 0;
- @override
- Widget build(BuildContext context) {
- return GestureDetector(
- child: Text(
- _handleBtnText(),
- style: const TextStyle(
- color: MyColor.c_25A6EE, fontSize: 14),
- ),
- onTap: () async{
- if (_countdownTime == 0) {
- if (!StringUtils.isPhoneNum(widget.phoneController.text)) {
- MyNavigator.showToast('请输入正确的手机号');
- return;
- }
- bool isPost = await getPhoneMsg();
- if(!isPost){
- return;
- }
- // print('可以发送了');
- _startCountdown();
- }
- },
- );
- }
- /// 获取验证码
- Future<bool> getPhoneMsg() async{
- try{
- var res = await MyApi.get().postPhoneMsg({
- 'mobile': widget.phoneController.text,
- 'scene': 23,
- });
- //print('$res.data');
- if( res.data ?? false){
- MyNavigator.showToast('验证码已发送');
- return true;
- }else{
- return false;
- }
- }catch(e){
- logger.e(e);
- return false;
- }
- }
- String _handleBtnText() {
- if (_countdownTime > 0) {
- return '剩余$_countdownTime秒';
- } else {
- return '获取验证码';
- }
- }
- //倒计时方法
- void _startCountdown() {
- //倒计时时间
- _countdownTime = widget.timeCount;
- if (_timer != null) {
- // 如果timer已存在要先取消置空
- _timer!.cancel();
- _timer = null;
- }
- _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
- if (_countdownTime < 1) {
- _timer?.cancel();
- } else {
- setState(() {
- _countdownTime -= 1;
- });
- }
- });
- }
- @override
- void dispose() {
- _timer?.cancel();
- _timer = null;
- super.dispose();
- }
- }
|