You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何添加并使用计时器?Stopwatch能否替代计时器?

Flutter中Stopwatch与Timer的使用解析

嘿,我来给你理清楚这两个工具的区别和用法,帮你搞定计时器需求~

一、Stopwatch能不能替代计时器?

先明确两个工具的核心定位:

  • Stopwatch:它的核心作用是测量时间间隔——说白了就是记录从start()到stop()之间的时长,本身不会主动触发任何回调逻辑,只是个纯粹的“时间记录器”。
  • 我们常说的“计时器”(一般指Timer):核心是定时触发任务,比如延迟N秒执行某个操作,或者每隔N秒重复执行一段逻辑。

所以结论很明确:

  • 如果你的需求是测量某段代码/操作的耗时,Stopwatch完全够用,而且简单直接;
  • 如果需要定时执行任务(比如倒计时、实时刷新时钟),Stopwatch没法直接替代Timer——因为它不会自己“提醒”你时间到了,得配合Timer才能实现这类实时更新的需求。

举个Stopwatch的基础用法(基于你给出的代码延伸):

var stopwatch = Stopwatch()..start();

// 执行你要测耗时的操作,比如网络请求、复杂计算
await fetchDataFromApi();

stopwatch.stop();
print('请求耗时:${stopwatch.elapsedMilliseconds} 毫秒');

二、如何在Flutter中使用Timer(计时器)

Timer主要分两种使用场景,我给你分别写示例:

1. 一次性延迟执行任务

比如用户点击按钮后,延迟2秒跳转到新页面:

ElevatedButton(
  onPressed: () {
    // 延迟2秒执行跳转
    Timer(const Duration(seconds: 2), () {
      Navigator.push(context, MaterialPageRoute(builder: (_) => const NewPage()));
    });
  },
  child: const Text('延迟跳转'),
)

2. 周期性重复执行任务

最常见的场景就是倒计时、实时时钟这类需要持续更新UI的功能,注意一定要在页面销毁时取消Timer,避免内存泄漏:

class CountdownPage extends StatefulWidget {
  const CountdownPage({super.key});

  @override
  State<CountdownPage> createState() => _CountdownPageState();
}

class _CountdownPageState extends State<CountdownPage> {
  late Timer _timer;
  int _remainingSeconds = 10;

  @override
  void initState() {
    super.initState();
    // 每隔1秒执行一次回调
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_remainingSeconds > 0) {
          _remainingSeconds--;
        } else {
          timer.cancel(); // 倒计时结束,取消计时器
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('倒计时完成!')),
          );
        }
      });
    });
  }

  @override
  void dispose() {
    _timer.cancel(); // 页面销毁时必须取消计时器
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('倒计时')),
      body: Center(
        child: Text(
          '$_remainingSeconds',
          style: const TextStyle(fontSize: 48),
        ),
      ),
    );
  }
}

3. Stopwatch + Timer 结合使用

如果想要实现“实时显示已运行时长”的功能,就可以用Stopwatch记录时间,再用Timer定期触发UI更新:

class StopwatchTimerPage extends StatefulWidget {
  const StopwatchTimerPage({super.key});

  @override
  State<StopwatchTimerPage> createState() => _StopwatchTimerPageState();
}

class _StopwatchTimerPageState extends State<StopwatchTimerPage> {
  late Timer _updateTimer;
  final Stopwatch _stopwatch = Stopwatch();

  @override
  void initState() {
    super.initState();
    _stopwatch.start();
    // 每隔100ms更新一次UI,让时间显示更流畅
    _updateTimer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
      setState(() {}); // 触发UI刷新
    });
  }

  @override
  void dispose() {
    _updateTimer.cancel();
    _stopwatch.stop();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final elapsed = _stopwatch.elapsed;
    return Scaffold(
      appBar: AppBar(title: const Text('实时计时器')),
      body: Center(
        child: Text(
          '已运行:${elapsed.inMinutes}:${(elapsed.inSeconds % 60).toString().padLeft(2, '0')}',
          style: const TextStyle(fontSize: 32),
        ),
      ),
    );
  }
}

内容的提问来源于stack exchange,提问作者Yigit Kader

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:39:27