import 'dart:async'; import 'package:eitc_erm_dental_flutter/exts.dart'; import 'package:flutter/material.dart'; ///计时按钮 class CountingButton extends StatefulWidget { final CountingButtonController controller; final VoidCallback? onPressed; final Widget Function(int count, bool isCounting) onGetChild; final ButtonStyle? buttonStyle; const CountingButton( {super.key, required this.controller, required this.onGetChild, this.onPressed, this.buttonStyle}); @override State createState() => _CountingButtonState(); } class _CountingButtonState extends State { @override void initState() { super.initState(); widget.controller.counter.addListener(() { setState(() {}); }); } @override void dispose() { super.dispose(); widget.controller.dispose(); } @override Widget build(BuildContext context) { return ElevatedButton( onPressed: _onPressed, style: widget.buttonStyle ?? ButtonStyle( backgroundColor: WidgetStatePropertyAll(context.primaryColor), elevation: const WidgetStatePropertyAll(0.0)), child: widget.onGetChild( widget.controller.counter.value, widget.controller.isCounting)); } void _onPressed() { if (widget.controller.counter.value > 0) { return; } widget.onPressed?.call(); } } class CountingButtonController { Timer? _timer; ValueNotifier? _counter; ValueNotifier get counter => _counter ??= ValueNotifier(-1); bool get isCounting => _timer != null; void start(int count) { _timer?.cancel(); _timer = Timer.periodic(Duration(seconds: 1), (t) { counter.value = t.tick; if (t.tick >= count) { stop(); } }); counter.value = 0; } void stop() { _timer?.cancel(); _timer = null; counter.value = -1; } void dispose() { _counter?.dispose(); _counter = null; } }