import 'dart:async'; import 'package:flutter/material.dart'; /// 带倒计时的发送按钮(常用于短信验证码)。 /// /// 倒计时结束后自动恢复可点击状态。 class CountDownButton extends StatefulWidget { const CountDownButton({ super.key, required this.onSend, this.label = '发送验证码', this.countingLabel = '重新发送', this.seconds = 60, }); final VoidCallback onSend; final String label; final String countingLabel; final int seconds; @override State createState() => _CountDownButtonState(); } class _CountDownButtonState extends State { int _remaining = 0; Timer? _timer; bool get _isCounting => _remaining > 0; void _start() { widget.onSend(); setState(() => _remaining = widget.seconds); _timer = Timer.periodic(const Duration(seconds: 1), (t) { if (_remaining <= 1) { t.cancel(); if (mounted) setState(() => _remaining = 0); } else { if (mounted) setState(() => _remaining--); } }); } @override void dispose() { _timer?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return TextButton( onPressed: _isCounting ? null : _start, child: Text( _isCounting ? '${widget.countingLabel}(${_remaining}s)' : widget.label, ), ); } }