如何使用Dio获取图片上传的剩余时间?
获取Dio上传剩余时间的实现方案
可以实现,核心是通过记录上传进度的时间节点,计算出实时上传速度,再用剩余待上传的字节数除以速度,就能得到剩余时间。结合你的现有代码,调整后的实现如下:
步骤1:定义需要的状态变量
在你的页面/组件的状态类中,添加几个变量用来记录上传相关的关键数据:
int _totalBytes = 0; int _lastSentBytes = 0; DateTime? _lastUpdateTime; double _uploadSpeed = 0.0; // 单位:字节/秒 String _remainingTime = "计算中...";
步骤2:在onSendProgress中计算剩余时间
修改你的上传进度回调逻辑,加入速度计算和剩余时间推导:
onSendProgress: (int sent, int total) { // 更新上传进度百分比 uploadProgress.value = "${(sent / total * 100).toStringAsFixed(0)}%"; _totalBytes = total; final now = DateTime.now(); // 计算实时上传速度(加入平滑处理,避免网络波动导致数值跳变) if (_lastUpdateTime != null && _lastSentBytes > 0) { final timeDiff = now.difference(_lastUpdateTime!).inMilliseconds / 1000; final bytesDiff = sent - _lastSentBytes; // 用加权平均方式平滑速度值,0.7和0.3的比例可以根据需求调整 _uploadSpeed = (_uploadSpeed * 0.7) + (bytesDiff / timeDiff) * 0.3; } // 更新上次记录的进度和时间 _lastSentBytes = sent; _lastUpdateTime = now; // 计算并格式化剩余时间 if (_uploadSpeed > 0 && total > sent) { final remainingBytes = total - sent; final remainingSeconds = remainingBytes / _uploadSpeed; // 把秒数转成时分秒格式 int hours = remainingSeconds ~/ 3600; int minutes = (remainingSeconds % 3600) ~/ 60; int seconds = (remainingSeconds % 60).toInt(); _remainingTime = ""; if (hours > 0) _remainingTime += "${hours}h "; _remainingTime += "${minutes}m ${seconds}s"; } else { _remainingTime = "计算中..."; } // 这里可以把_remainingTime赋值给对应的UI变量,比如remainingTime.value = _remainingTime; },
关键说明
- 速度计算加入了平滑加权处理,避免网络突然波动导致剩余时间出现大幅跳变,让显示更稳定
- 初始上传阶段(还没积累足够数据)会显示“计算中...”,避免出现不合理的时间值
- 剩余时间格式化为时分秒的形式,比单纯显示秒数更直观
内容的提问来源于stack exchange,提问作者Pravin Fofariya
相关产品推荐
相关产品推荐

