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

Flutter定时器最佳实现方案咨询:两种计时场景需求

计时功能实现方案探讨

我正在研究计时功能的不同实现方案,还没确定最优解。我的业务场景需要两种定时器:

  • 从3到0的倒计时
  • 支持暂停的从0到10的正计时

我尝试了三种实现方式,各有疑问:

1. Animation实现

已完成功能,但我搞不懂为什么要用TweenAnimationBuilder来更新文本——明明用setState也能实现文本更新。
代码示例:

TweenAnimationBuilder<Duration>(
  duration: const Duration(seconds: 10),
  tween: Tween(
      begin: const Duration(seconds: 0), end: const Duration(seconds: 10)),
  onEnd: () {},
)

2. Timer实现

这是最常用的方式,但在毫秒级计时时,定时器的触发时机不够准确。
代码示例:

Timer.periodic(
  const Duration(milliseconds: 1),
  (Timer timer) {
    if (start == 0) {
      setState(() {
        timer.cancel();
      });
    } else {
      setState(() {
        start--;
      });
    }
  },
);

3. Stopwatch实现

它能精准计算两个时刻之间的时间差,但我不知道怎么把它适配到我的计时场景里。
代码示例:

final stopwatch = Stopwatch();
stopwatch.stop();
print(stopwatch.isRunning); // false
Duration elapsed = stopwatch.elapsed;
await Future.delayed(const Duration(seconds: 1));
assert(stopwatch.elapsed == elapsed); // 这段时间未被计入
stopwatch.start();

Timer与Stopwatch的核心说明

  • Timer:用于在指定延迟后单次或周期性执行任务,但它依赖于事件循环,无法保证绝对精准的触发时机——尤其是毫秒级场景下,系统负载、事件队列阻塞都会导致触发延迟。
  • Stopwatch:是高精度时间测量工具,基于系统单调时钟(不受系统时间调整影响),能准确记录启动到停止的流逝时间,适合精准计算时间差的场景,但本身不具备定时触发任务的能力,需要结合其他机制更新UI。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:16:16