import 'dart:async'; import 'package:zhiying_comm/zhiying_comm.dart'; import 'package:flutter/material.dart'; class VcodeWidget extends StatefulWidget { // 按钮文字 final String btnText; // 按钮等待文字 final String btnAwaitText; // 按钮文字的颜色 final String btnTextColor; // 按钮的背景颜色 final String color; // 禁用文字的颜色 final String disabledTextColor; // 禁用按钮的背景颜色 final String disabledColor; // 等待时长 final int awaitTime; // 高 final double height; final double width; final double border; final OnClickListener onCallBack; const VcodeWidget({ this.btnText, this.btnAwaitText, this.btnTextColor, this.color, this.disabledTextColor, this.disabledColor, this.awaitTime, this.onCallBack, this.border = 8, this.height = 30, this.width = 82}); @override _VcodeWidgetState createState() => _VcodeWidgetState(); } class _VcodeWidgetState extends State { /// 是否可以获取验证码 bool _canGetVcode = true; /// 倒计时 Timer _timer; int _countdownTime = 0; /// 获取验证码 void _getVcodeOnClick() { // print('获取验证码'); if(widget.onCallBack.onVcodeClick()) { int count = widget?.awaitTime ?? 60; startCountdownTimer(count); } } /// 开始倒计时 void startCountdownTimer(int countTime) { const oneSec = const Duration(seconds: 1); setState(() { _canGetVcode = false; _countdownTime = countTime; }); var callback = (timer) => { setState(() { if (_countdownTime < 1) { _canGetVcode = true; _timer.cancel(); _countdownTime = countTime; // 重置倒计时 } else { _countdownTime = _countdownTime - 1; _canGetVcode = false; } }) }; _timer = Timer.periodic(oneSec, callback); } @override void dispose() { _timer?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return Material( child: Container( alignment: Alignment.center, height: widget?.height ?? 30, width: widget?.width ?? 82, margin: const EdgeInsets.only(right: 6), child: RaisedButton( onPressed: _canGetVcode ? ()=> _getVcodeOnClick() : null, padding: EdgeInsets.zero, child: Text(_canGetVcode ? ( widget?.btnText ?? '获取验证码') : '${_countdownTime}${widget?.btnAwaitText ?? '秒'}', style: TextStyle(color: HexColor.fromHex( widget?.btnTextColor ?? '#FFFFFF'), fontSize: 11)), disabledTextColor: HexColor.fromHex( widget?.disabledTextColor ?? '#FFFFFF'), disabledColor: HexColor.fromHex( widget?.disabledColor ?? '#DDDDDD'), color: HexColor.fromHex( widget?.color ?? '#FF4343'), textColor: HexColor.fromHex( widget?.btnTextColor ?? '#FFFFFF'), elevation: 4, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(widget?.border ?? 8)), ), ), ); } } abstract class OnClickListener{ bool onVcodeClick(); }