You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.6 KiB

2 years ago
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. class TimerWidget extends StatefulWidget {
  4. const TimerWidget({
  5. Key? key,
  6. required this.fontSize,
  7. required this.color,
  8. }) : super(key: key);
  9. final double fontSize;
  10. final Color color;
  11. @override
  12. _TimerWidgetState createState() => _TimerWidgetState();
  13. }
  14. class _TimerWidgetState extends State<TimerWidget> {
  15. late final Timer _timer;
  16. int _start = 0;
  17. void startTimer() {
  18. _timer = Timer.periodic(
  19. const Duration(seconds: 1),
  20. (Timer timer) => setState(() => _start++),
  21. );
  22. }
  23. String printDuration() {
  24. var duration = Duration(seconds: _start);
  25. String twoDigits(int n) => n.toString().padLeft(2, "0");
  26. String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
  27. String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
  28. return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
  29. }
  30. @override
  31. void initState() {
  32. startTimer();
  33. super.initState();
  34. }
  35. @override
  36. void dispose() {
  37. _timer.cancel();
  38. super.dispose();
  39. }
  40. @override
  41. Widget build(BuildContext context) {
  42. return Center(
  43. child: Row(
  44. mainAxisSize: MainAxisSize.min,
  45. children: [
  46. Text(
  47. printDuration(),
  48. style: TextStyle(
  49. fontSize: widget.fontSize,
  50. color: widget.color,
  51. ),
  52. ),
  53. const SizedBox(width: 8),
  54. Icon(
  55. Icons.timer,
  56. color: widget.color,
  57. size: widget.fontSize * 1.3,
  58. )
  59. ],
  60. ),
  61. );
  62. }
  63. }