123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- import 'dart:async';
- 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(Theme.of(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;
- }
- }
|