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

Flutter使用stop_watch_timer包时出现整数下溢错误

问题解决:stop_watch_timer 减时出现负数的修复

直接调用setPresetMinuteTime(-5)会导致秒表时间出现负数,原因是该方法仅直接修改预设偏移量,不会校验总时间是否低于0。当当前总时间为0时,减去5分钟的偏移量会让总时间变成-300000毫秒(即-5分钟),而包的时间格式化逻辑会将负数转换为-1:55:00这类异常格式。

修复方案

在减时操作前先获取当前总时间,确保调整后的时间不小于0,再设置合法的预设值:

修改减5分钟按钮的onPressed逻辑:

Padding(
  padding: const EdgeInsets.symmetric(horizontal: 5),
  child: ElevatedButton(
    style: ElevatedButton.styleFrom(backgroundColor: Colors.amber),
    onPressed: () {
      // 获取当前秒表总时间(毫秒)
      final currentTotalMs = _stopWatchTimer.getRawTime().value;
      // 计算减去5分钟后的时间,最低为0
      final newTotalMs = max(0, currentTotalMs - 5 * 60 * 1000);
      // 清除原有预设,设置新的预设偏移量(总时间 - 基础时间)
      _stopWatchTimer.clearPresetTime();
      _stopWatchTimer.setPresetTime(
        milliseconds: newTotalMs - _stopWatchTimer.baseTime.value
      );
    },
    child: const Text('-5 Minutes'),
  ),
)

补充说明

  • getRawTime().value获取当前秒表的累计总时间(包含预设偏移的毫秒数)
  • baseTime.value是秒表的初始基础时间,预设偏移量是基于这个值的增量
  • 通过max(0, ...)确保时间不会低于0,避免负数异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 05:02:27