flutter如何实现stopwatch计时器功能

在Flutter中如何实现一个精确的Stopwatch计时器功能?

我需要在应用中添加一个计时器,可以开始、暂停、重置,并显示经过的时间。尝试过使用Timer类,但精度不够,暂停后继续计时也不太准确。

请问有没有完整的实现方案?最好能包括UI显示和逻辑控制部分,同时保证计时精度。是否需要使用Dart的Stopwatch类?该如何将它和Widget状态结合起来?

2 回复

在Flutter中实现Stopwatch计时器功能很简单:

  1. 使用内置的Stopwatch类:
Stopwatch _stopwatch = Stopwatch();
String _timeString = "00:00:00";
  1. 核心方法:
void _startTimer() {
  _stopwatch.start();
  Timer.periodic(Duration(milliseconds: 30), (timer) {
    setState(() {
      _timeString = _formatTime(_stopwatch.elapsedMilliseconds);
    });
  });
}

void _stopTimer() {
  _stopwatch.stop();
}

void _resetTimer() {
  _stopwatch.reset();
  setState(() {
    _timeString = "00:00:00";
  });
}
  1. 时间格式化:
String _formatTime(int milliseconds) {
  int hundreds = (milliseconds / 10).truncate();
  int seconds = (hundreds / 100).truncate();
  int minutes = (seconds / 60).truncate();
  
  return "${minutes.toString().padLeft(2, '0')}:"
         "${(seconds % 60).toString().padLeft(2, '0')}:"
         "${(hundreds % 100).toString().padLeft(2, '0')}";
}
  1. UI中使用Text显示_timeString即可。

这样就实现了基本的计时、暂停、重置功能,精度到毫秒级。

更多关于flutter如何实现stopwatch计时器功能的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中实现Stopwatch计时器功能非常简单,可以使用Dart内置的Stopwatch类,结合Timer实现实时更新。以下是完整实现:

1. 基本实现代码

import 'package:flutter/material.dart';

class StopwatchPage extends StatefulWidget {
  @override
  _StopwatchPageState createState() => _StopwatchPageState();
}

class _StopwatchPageState extends State<StopwatchPage> {
  Stopwatch _stopwatch = Stopwatch();
  Timer? _timer;
  String _timeString = '00:00:00';

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  // 格式化时间显示
  String _formatTime() {
    var milliseconds = _stopwatch.elapsedMilliseconds;
    var hours = (milliseconds / (1000 * 60 * 60)).floor();
    var minutes = ((milliseconds % (1000 * 60 * 60)) / (1000 * 60)).floor();
    var seconds = ((milliseconds % (1000 * 60)) / 1000).floor();
    
    return '${hours.toString().padLeft(2, '0')}:'
           '${minutes.toString().padLeft(2, '0')}:'
           '${seconds.toString().padLeft(2, '0')}';
  }

  // 开始计时
  void _startTimer() {
    _stopwatch.start();
    _timer = Timer.periodic(Duration(milliseconds: 100), (timer) {
      setState(() {
        _timeString = _formatTime();
      });
    });
  }

  // 暂停计时
  void _pauseTimer() {
    _stopwatch.stop();
    _timer?.cancel();
  }

  // 重置计时器
  void _resetTimer() {
    _stopwatch.reset();
    setState(() {
      _timeString = '00:00:00';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Stopwatch')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              _timeString,
              style: TextStyle(fontSize: 48, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 30),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                if (!_stopwatch.isRunning)
                  ElevatedButton(
                    onPressed: _startTimer,
                    child: Text('开始'),
                  ),
                if (_stopwatch.isRunning)
                  ElevatedButton(
                    onPressed: _pauseTimer,
                    child: Text('暂停'),
                  ),
                SizedBox(width: 20),
                ElevatedButton(
                  onPressed: _resetTimer,
                  child: Text('重置'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

2. 关键要点说明

  • Stopwatch类:提供start()stop()reset()方法和elapsedMilliseconds属性
  • Timer.periodic:每100毫秒更新一次显示,确保界面流畅
  • 状态管理:使用setState()触发界面重绘
  • 内存管理:在dispose()中取消定时器,防止内存泄漏

3. 使用方法

// 在应用中使用
void main() {
  runApp(MaterialApp(
    home: StopwatchPage(),
  ));
}

这个实现包含了开始、暂停、重置功能,时间格式为"时:分:秒",可以根据需要调整更新频率和显示格式。

回到顶部