timer_page.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. import 'dart:async';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter_clock/model/timer_data.dart';
  4. import 'package:flutter_clock/model/timer_settings.dart';
  5. import 'package:flutter_clock/pages/timer/timer_settings_page.dart';
  6. import 'package:flutter_clock/utils/audio_manager.dart';
  7. import 'package:flutter_clock/utils/screen_manager.dart';
  8. import 'package:flutter_clock/utils/background_timer_service.dart';
  9. import 'package:flutter_clock/utils/notification_manager.dart';
  10. /// Description: 倒计时页面
  11. /// Time : 04/06/2025 Sunday
  12. /// Author : liuyuqi.gov@msn.cn
  13. class TimerPage extends StatefulWidget {
  14. @override
  15. _TimerPageState createState() => _TimerPageState();
  16. }
  17. enum TimerState { prepare, running, pause, finish }
  18. class _TimerPageState extends State<TimerPage> with WidgetsBindingObserver {
  19. // Timer duration values
  20. int _hours = 0;
  21. int _minutes = 10;
  22. int _seconds = 0;
  23. // For timer controller
  24. TimerState timerState = TimerState.prepare;
  25. int _remainingSeconds = 0;
  26. // Total timer duration in seconds (for progress calculation)
  27. int _totalDurationSeconds = 0;
  28. // Background services
  29. final BackgroundTimerService _backgroundTimerService = BackgroundTimerService();
  30. final NotificationManager _notificationManager = NotificationManager();
  31. // Settings
  32. late TimerSettings _settings;
  33. bool _settingsLoaded = false;
  34. final AudioManager _audioManager = AudioManager();
  35. // Wheel controllers
  36. final FixedExtentScrollController _hoursController =
  37. FixedExtentScrollController(initialItem: 0);
  38. final FixedExtentScrollController _minutesController =
  39. FixedExtentScrollController(initialItem: 10);
  40. final FixedExtentScrollController _secondsController =
  41. FixedExtentScrollController(initialItem: 0);
  42. @override
  43. void initState() {
  44. super.initState();
  45. WidgetsBinding.instance.addObserver(this);
  46. _initializeBackgroundTimer();
  47. _loadSettings();
  48. _restoreTimerState();
  49. }
  50. @override
  51. void dispose() {
  52. _audioManager.dispose();
  53. _backgroundTimerService.dispose();
  54. if (ScreenManager.isWakeLockEnabled) {
  55. ScreenManager.disableWakeLock();
  56. }
  57. WidgetsBinding.instance.removeObserver(this);
  58. _hoursController.dispose();
  59. _minutesController.dispose();
  60. _secondsController.dispose();
  61. super.dispose();
  62. }
  63. @override
  64. void didChangeAppLifecycleState(AppLifecycleState state) {
  65. // No additional handling required as background service handles the state
  66. }
  67. /// Restore timer state from persistent storage
  68. Future<void> _restoreTimerState() async {
  69. final timerData = await TimerData.load();
  70. if (timerData.isRunning) {
  71. setState(() {
  72. timerState = TimerState.running;
  73. _remainingSeconds = timerData.calculateRemainingSeconds();
  74. _totalDurationSeconds = _backgroundTimerService.totalDurationSeconds;
  75. });
  76. } else if (timerData.isPaused && timerData.pausedRemaining != null) {
  77. setState(() {
  78. timerState = TimerState.pause;
  79. _remainingSeconds = timerData.pausedRemaining!;
  80. _totalDurationSeconds = _backgroundTimerService.totalDurationSeconds;
  81. });
  82. }
  83. }
  84. /// Initialize the background timer service
  85. Future<void> _initializeBackgroundTimer() async {
  86. await _backgroundTimerService.initialize(
  87. onTimerComplete: _timerCompleted,
  88. onTimerTick: (remainingSeconds) {
  89. setState(() {
  90. _remainingSeconds = remainingSeconds;
  91. if (remainingSeconds <= 0 && timerState != TimerState.finish) {
  92. timerState = TimerState.finish;
  93. }
  94. });
  95. },
  96. );
  97. }
  98. Future<void> _loadSettings() async {
  99. _settings = await TimerSettings.loadSettings();
  100. setState(() {
  101. _settingsLoaded = true;
  102. });
  103. }
  104. /// Start a new timer or resume an existing paused timer
  105. void _startTimer(bool resumed) {
  106. if (resumed) {
  107. setState(() {
  108. timerState = TimerState.running;
  109. });
  110. _backgroundTimerService.resumeTimer(_remainingSeconds, _totalDurationSeconds);
  111. } else {
  112. final totalSeconds = _hours * 3600 + _minutes * 60 + _seconds;
  113. if (totalSeconds <= 0) return;
  114. setState(() {
  115. timerState = TimerState.running;
  116. _remainingSeconds = totalSeconds;
  117. _totalDurationSeconds = totalSeconds;
  118. });
  119. _backgroundTimerService.startTimer(totalSeconds);
  120. }
  121. }
  122. /// Pause the running timer
  123. void _pauseTimer() {
  124. _backgroundTimerService.pauseTimer();
  125. setState(() {
  126. timerState = TimerState.pause;
  127. });
  128. }
  129. /// Reset the timer to initial state
  130. void _resetTimer() {
  131. _backgroundTimerService.cancelTimer();
  132. _audioManager.stopSound();
  133. _audioManager.stopVibration();
  134. _notificationManager.stopVibration();
  135. setState(() {
  136. timerState = TimerState.prepare;
  137. });
  138. }
  139. /// Handle timer completion
  140. Future<void> _timerCompleted() async {
  141. setState(() {
  142. timerState = TimerState.finish;
  143. });
  144. // Play sound and vibrate
  145. if (_settings.vibrate) {
  146. _notificationManager.notifyTimerCompletion();
  147. }
  148. _audioManager.playSound(_settings.sound, _settings.volume, _settings.loop);
  149. // If loop is enabled, restart the timer
  150. if (_settings.loop) {
  151. Future.delayed(Duration(seconds: 5), () {
  152. _audioManager.stopSound();
  153. _notificationManager.stopVibration();
  154. });
  155. _startTimer(false);
  156. }
  157. }
  158. String _formatTime(int seconds) {
  159. final hours = seconds ~/ 3600;
  160. final minutes = (seconds % 3600) ~/ 60;
  161. final secs = seconds % 60;
  162. return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
  163. }
  164. @override
  165. Widget build(BuildContext context) {
  166. if (!_settingsLoaded) {
  167. return Center(child: CircularProgressIndicator());
  168. }
  169. if (timerState != TimerState.prepare) {
  170. return _buildCountdownView();
  171. } else {
  172. return _buildTimerSetupView();
  173. }
  174. }
  175. Widget _buildTimerSetupView() {
  176. return Scaffold(
  177. backgroundColor: Colors.white,
  178. body: Column(
  179. mainAxisAlignment: MainAxisAlignment.center,
  180. children: [
  181. Expanded(
  182. child: Row(
  183. children: [
  184. Expanded(
  185. child: _buildTimerWheel(
  186. _hoursController,
  187. List.generate(24, (index) => index),
  188. (value) {
  189. setState(() {
  190. _hours = value;
  191. });
  192. },
  193. 'H',
  194. ),
  195. ),
  196. Expanded(
  197. child: _buildTimerWheel(
  198. _minutesController,
  199. List.generate(60, (index) => index),
  200. (value) {
  201. setState(() {
  202. _minutes = value;
  203. });
  204. },
  205. 'M',
  206. ),
  207. ),
  208. Expanded(
  209. child: _buildTimerWheel(
  210. _secondsController,
  211. List.generate(60, (index) => index),
  212. (value) {
  213. setState(() {
  214. _seconds = value;
  215. });
  216. },
  217. 'S',
  218. ),
  219. ),
  220. ],
  221. ),
  222. ),
  223. SizedBox(height: 20),
  224. Padding(
  225. padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 20),
  226. child: Row(
  227. mainAxisAlignment: MainAxisAlignment.spaceAround,
  228. children: [
  229. _buildCircleButton(
  230. Icons.phone_android,
  231. Colors.grey[600]!,
  232. () {
  233. ScreenManager.toggleWakeLock();
  234. setState(() {});
  235. },
  236. isActive: ScreenManager.isWakeLockEnabled,
  237. ),
  238. _buildCircleButton(
  239. Icons.play_arrow,
  240. Colors.blue,
  241. () => _startTimer(false),
  242. ),
  243. _buildCircleButton(
  244. Icons.settings,
  245. Colors.grey[600]!,
  246. () async {
  247. final result = await Navigator.push(
  248. context,
  249. MaterialPageRoute(
  250. builder: (context) =>
  251. TimerSettingsPage(settings: _settings)),
  252. );
  253. if (result != null) {
  254. setState(() {
  255. _settings = result;
  256. });
  257. }
  258. },
  259. ),
  260. ],
  261. ),
  262. ),
  263. ],
  264. ),
  265. );
  266. }
  267. Widget _buildCountdownView() {
  268. final totalMinutes = _remainingSeconds ~/ 60;
  269. return Scaffold(
  270. backgroundColor: Colors.white,
  271. body: Column(
  272. mainAxisAlignment: MainAxisAlignment.center,
  273. children: [
  274. Expanded(
  275. child: Center(
  276. child: Column(
  277. mainAxisAlignment: MainAxisAlignment.center,
  278. children: [
  279. Container(
  280. width: 300,
  281. height: 300,
  282. decoration: BoxDecoration(
  283. shape: BoxShape.circle,
  284. border: Border.all(
  285. color: Colors.blue.withOpacity(0.3),
  286. width: 3,
  287. ),
  288. ),
  289. child: Stack(
  290. alignment: Alignment.center,
  291. children: [
  292. // Timer progress
  293. SizedBox(
  294. width: 300,
  295. height: 300,
  296. child: CircularProgressIndicator(
  297. value: timerState == TimerState.finish
  298. ? 1
  299. : _totalDurationSeconds > 0
  300. ? _remainingSeconds / _totalDurationSeconds
  301. : 0,
  302. strokeWidth: 5,
  303. backgroundColor: Colors.grey.withOpacity(0.1),
  304. color: Colors.blue,
  305. ),
  306. ),
  307. // Time display
  308. Column(
  309. mainAxisAlignment: MainAxisAlignment.center,
  310. children: [
  311. Text(
  312. _formatTime(_remainingSeconds),
  313. style: TextStyle(
  314. fontSize: 40, fontWeight: FontWeight.bold),
  315. ),
  316. Text(
  317. 'Total ${totalMinutes} minutes',
  318. style:
  319. TextStyle(fontSize: 16, color: Colors.grey),
  320. ),
  321. ],
  322. ),
  323. // Indicator dot
  324. Positioned(
  325. bottom: 0,
  326. child: Container(
  327. width: 20,
  328. height: 20,
  329. decoration: BoxDecoration(
  330. color: Colors.blue,
  331. shape: BoxShape.circle,
  332. ),
  333. ),
  334. ),
  335. ],
  336. ),
  337. ),
  338. ],
  339. ),
  340. ),
  341. ),
  342. Padding(
  343. padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 20),
  344. child: Row(
  345. mainAxisAlignment: MainAxisAlignment.spaceAround,
  346. children: [
  347. // 唤醒屏幕
  348. _buildCircleButton(
  349. Icons.phone_android,
  350. Colors.grey[600]!,
  351. () {
  352. ScreenManager.toggleWakeLock();
  353. setState(() {});
  354. },
  355. isActive: ScreenManager.isWakeLockEnabled,
  356. ),
  357. // 暂停/开始
  358. timerState == TimerState.running
  359. ? _buildCircleButton(
  360. Icons.pause,
  361. Colors.blue,
  362. () => _pauseTimer(),
  363. )
  364. : _buildCircleButton(
  365. Icons.play_arrow,
  366. Colors.blue,
  367. () => _startTimer(true),
  368. ),
  369. // 重置
  370. _buildCircleButton(
  371. Icons.stop,
  372. Colors.red,
  373. () => _resetTimer(),
  374. ),
  375. ],
  376. ),
  377. ),
  378. ],
  379. ),
  380. );
  381. }
  382. Widget _buildCircleButton(IconData icon, Color color, VoidCallback onPressed,
  383. {bool isActive = false}) {
  384. return Container(
  385. width: 70,
  386. height: 70,
  387. decoration: BoxDecoration(
  388. shape: BoxShape.circle,
  389. color: isActive ? color : Colors.white,
  390. boxShadow: [
  391. BoxShadow(
  392. color: Colors.black.withOpacity(0.1),
  393. blurRadius: 8,
  394. offset: Offset(0, 2),
  395. ),
  396. ],
  397. ),
  398. child: IconButton(
  399. icon: Icon(icon, size: 30),
  400. color: isActive ? Colors.white : color,
  401. onPressed: onPressed,
  402. ),
  403. );
  404. }
  405. Widget _buildTimerWheel(
  406. FixedExtentScrollController controller,
  407. List<int> items,
  408. ValueChanged<int> onChanged,
  409. String unit,
  410. ) {
  411. return Column(
  412. children: [
  413. Expanded(
  414. child: Container(
  415. decoration: BoxDecoration(
  416. border: Border(
  417. top: BorderSide(color: Colors.grey.withOpacity(0.3), width: 1),
  418. bottom:
  419. BorderSide(color: Colors.grey.withOpacity(0.3), width: 1),
  420. ),
  421. ),
  422. child: Stack(
  423. children: [
  424. // Center highlight
  425. Positioned.fill(
  426. child: Center(
  427. child: Container(
  428. height: 50,
  429. decoration: BoxDecoration(
  430. color: Colors.blue.withOpacity(0.1),
  431. borderRadius: BorderRadius.circular(8),
  432. ),
  433. ),
  434. ),
  435. ),
  436. ListWheelScrollView(
  437. controller: controller,
  438. physics: FixedExtentScrollPhysics(),
  439. diameterRatio: 1.5,
  440. itemExtent: 50,
  441. children: items.map((value) {
  442. return Center(
  443. child: Text(
  444. value.toString().padLeft(2, '0'),
  445. style: TextStyle(
  446. fontSize: 30,
  447. color: Colors.black,
  448. fontWeight: FontWeight.w500,
  449. ),
  450. ),
  451. );
  452. }).toList(),
  453. onSelectedItemChanged: onChanged,
  454. ),
  455. ],
  456. ),
  457. ),
  458. ),
  459. SizedBox(height: 8),
  460. Text(
  461. unit,
  462. style: TextStyle(
  463. fontSize: 18,
  464. fontWeight: FontWeight.bold,
  465. ),
  466. ),
  467. ],
  468. );
  469. }
  470. }