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
相关产品推荐
相关产品推荐

