activity_countdown_txt_view.dart 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import 'package:flutter/material.dart';
  2. class ActivityCountdownTextView extends StatefulWidget {
  3. final Duration duration;
  4. final TextStyle? textStyle;
  5. final BoxDecoration? timeBgBoxDecoration;
  6. final double? timeItemWidth;
  7. final double? timeItemHeight;
  8. final BoxFit bgFit;
  9. final EdgeInsetsGeometry contentPadding;
  10. final Widget? separator;
  11. const ActivityCountdownTextView({
  12. super.key,
  13. required this.duration,
  14. this.timeBgBoxDecoration,
  15. this.textStyle,
  16. this.timeItemWidth,
  17. this.timeItemHeight,
  18. this.bgFit = BoxFit.contain,
  19. this.contentPadding = const EdgeInsets.all(4),
  20. this.separator,
  21. });
  22. @override
  23. State<ActivityCountdownTextView> createState() =>
  24. _ActivityCountdownTxtViewState();
  25. }
  26. class _ActivityCountdownTxtViewState extends State<ActivityCountdownTextView> {
  27. late Duration _remaining;
  28. @override
  29. void didUpdateWidget(covariant ActivityCountdownTextView oldWidget) {
  30. super.didUpdateWidget(oldWidget);
  31. if (oldWidget.duration != widget.duration) {
  32. setState(() {
  33. _remaining = widget.duration;
  34. });
  35. }
  36. }
  37. @override
  38. void initState() {
  39. super.initState();
  40. _remaining = widget.duration;
  41. }
  42. String _twoDigits(int n) => n.toString().padLeft(2, '0');
  43. /// 毫秒显示三位 (000–999)
  44. String _threeDigitsMilli(int n) => n.toString().padLeft(3, '0');
  45. @override
  46. Widget build(BuildContext context) {
  47. final minutes = _twoDigits(_remaining.inMinutes.remainder(60));
  48. final seconds = _twoDigits(_remaining.inSeconds.remainder(60));
  49. final milliseconds =
  50. _threeDigitsMilli(_remaining.inMilliseconds.remainder(1000));
  51. return Row(
  52. mainAxisSize: MainAxisSize.min,
  53. children: [
  54. _buildTimeBox(minutes),
  55. _buildSeparator(),
  56. _buildTimeBox(seconds),
  57. _buildSeparator(),
  58. _buildTimeBox(milliseconds),
  59. ],
  60. );
  61. }
  62. Widget _buildTimeBox(String text) {
  63. return Container(
  64. width: widget.timeItemWidth,
  65. height: widget.timeItemHeight,
  66. alignment: Alignment.center,
  67. padding: widget.contentPadding,
  68. decoration: widget.timeBgBoxDecoration,
  69. child: Center(
  70. child: Text(
  71. text,
  72. maxLines: 1,
  73. style: widget.textStyle ??
  74. const TextStyle(
  75. fontSize: 20,
  76. fontWeight: FontWeight.bold,
  77. color: Colors.white),
  78. ),
  79. ),
  80. );
  81. }
  82. Widget _buildSeparator() {
  83. return widget.separator ??
  84. const SizedBox(
  85. width: 4,
  86. );
  87. }
  88. @override
  89. void dispose() {
  90. super.dispose();
  91. }
  92. }