Flutter中点击TextButton实现秒表启停功能求助
Flutter 秒表功能实现方案
要实现点击按钮启停秒表的功能,你需要将TimerScreen从StatelessWidget改为StatefulWidget(因为需要维护计时状态),结合Stopwatch和Timer来完成逻辑。以下是修改后的完整代码:
import 'dart:async'; import 'package:flutter/material.dart'; class TimerScreen extends StatefulWidget { const TimerScreen({super.key}); @override State<TimerScreen> createState() => _TimerScreenState(); } class _TimerScreenState extends State<TimerScreen> { // 秒表实例,用于跟踪流逝时间 final Stopwatch _stopwatch = Stopwatch(); // 定时刷新UI的计时器 Timer? _timer; // 显示的时间字符串,格式mm:ss String _displayTime = '00:00'; // 标记秒表是否正在运行 bool _isRunning = false; // 格式化流逝时间为mm:ss格式 void _updateTimer() { final milliseconds = _stopwatch.elapsedMilliseconds; final minutes = (milliseconds ~/ 60000).toString().padLeft(2, '0'); final seconds = ((milliseconds % 60000) ~/ 1000).toString().padLeft(2, '0'); setState(() { _displayTime = '$minutes:$seconds'; }); } // 处理按钮点击逻辑 void _toggleStopwatch() { setState(() { if (_isRunning) { // 停止计时:停止秒表和刷新计时器 _stopwatch.stop(); _timer?.cancel(); } else { // 开始计时:重置并启动秒表,启动每秒刷新的计时器 _stopwatch.reset(); _stopwatch.start(); _timer = Timer.periodic(const Duration(seconds: 1), (timer) { _updateTimer(); }); } _isRunning = !_isRunning; }); } @override void dispose() { // 页面销毁时取消计时器,防止内存泄漏 _timer?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text( 'Trainer', style: TextStyle(color: Colors.deepOrangeAccent), ), actions: [ IconButton( onPressed: () { showDialog( context: context, builder: (context) => AlertDialog( actions: [ Center( child: TextButton( onPressed: () {}, child: const Text('2'), ), ), Center( child: TextButton( onPressed: () {}, child: const Text('3'), ), ), ], title: const Text('Choose algset:'), ), ); }, icon: const Icon( Icons.add_circle_outline, color: Colors.deepOrangeAccent, ), splashColor: Colors.transparent, highlightColor: Colors.transparent, ), ], ), body: Column( children: [ Container( height: 60, width: double.infinity, child: const Center( child: Text( "Testing", style: TextStyle(fontSize: 25), ), ), ), const SizedBox(height: 10), Container( height: 665, width: double.infinity, child: Center( child: Padding( padding: const EdgeInsets.only(bottom: 145.0), child: TextButton( onPressed: _toggleStopwatch, // 绑定点击事件 child: Text( _displayTime, // 使用动态更新的时间字符串 style: const TextStyle(fontSize: 50, color: Colors.white), ), ), ), ), ), ], ), ); } }
关键逻辑说明
Stopwatch类:负责底层的时间跟踪,它的start()、stop()、reset()方法控制计时状态,elapsedMilliseconds可以获取流逝的总毫秒数。Timer.periodic:每秒触发一次_updateTimer方法,更新UI显示的时间字符串,因为Stopwatch本身不会主动通知UI更新。- 状态管理:
_isRunning变量控制按钮的切换逻辑,setState()触发UI重建,更新显示的时间。 - 内存泄漏防护:在
dispose()方法中取消Timer,避免页面销毁后计时器仍在运行。
内容的提问来源于stack exchange,提问作者Spicy Pumpkin
相关产品推荐
相关产品推荐

