count_down_text.dart 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. ///倒计时文本
  4. class CountDownText extends StatefulWidget {
  5. final TextStyle? textStyle;
  6. final CountDownTextController controller;
  7. const CountDownText({super.key, required this.controller, this.textStyle});
  8. @override
  9. State<CountDownText> createState() => _CountDownTextState();
  10. }
  11. class _CountDownTextState extends State<CountDownText> {
  12. @override
  13. void initState() {
  14. super.initState();
  15. widget.controller.countText.addListener(_onUpdateCountText);
  16. }
  17. void _onUpdateCountText() {
  18. setState(() {});
  19. }
  20. @override
  21. void dispose() {
  22. super.dispose();
  23. widget.controller.countText.removeListener(_onUpdateCountText);
  24. widget.controller.stopCount();
  25. }
  26. @override
  27. Widget build(BuildContext context) {
  28. return Text(
  29. widget.controller.countText.value,
  30. style: widget.textStyle,
  31. );
  32. }
  33. }
  34. class CountDownTextController {
  35. ValueNotifier<String> countText = ValueNotifier("");
  36. void Function(int tick, bool complete)? onCount;
  37. Timer? _countTimer;
  38. CountDownTextController(this.onCount);
  39. bool get isCounting => _countTimer != null;
  40. void startCount(int time) {
  41. if (isCounting) {
  42. return;
  43. }
  44. if (time <= 0) {
  45. onCount?.call(0, true);
  46. return;
  47. }
  48. _countTimer = Timer.periodic(const Duration(seconds: 1), (tick) {
  49. int left = time - tick.tick;
  50. bool compelte = left <= 0;
  51. if (compelte) {
  52. _timeUp();
  53. } else {
  54. countText.value = "$left";
  55. }
  56. onCount?.call(tick.tick, compelte);
  57. });
  58. countText.value = "$time";
  59. }
  60. void stopCount() {
  61. _countTimer?.cancel();
  62. _countTimer = null;
  63. countText.value = "";
  64. }
  65. void _timeUp() {
  66. stopCount();
  67. }
  68. }