12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- 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<CountingButton> createState() => _CountingButtonState();
- }
- class _CountingButtonState extends State<CountingButton> {
- @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<int>? _counter;
- ValueNotifier<int> 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;
- }
- }
|