Flutter如何配置dio包?遇到onProgress参数未定义错误该怎么解决?
Dio包download方法onProgress参数未定义报错解决方案
该报错的核心原因是你使用的dio 5.0及以上版本做了不兼容更新,移除了download方法原生的onProgress命名参数,将下载进度回调统一整合到了options配置项的onReceiveProgress属性中。
修正后代码
Future<void> downloadFile() async { Dio dio = Dio(); try { var dir = await getApplicationDocumentsDirectory(); await dio.download( imgUrl, "${dir.path}/myimage.jpg", options: Options( onReceiveProgress: (rec, total) { print("Rec: $rec , Total: $total"); setState(() { downloading = true; progressString = ((rec / total) * 100).toStringAsFixed(0) + "%"; }); }, ) ); } catch (e) { print(e); } setState(() { downloading = false; progressString = "Completed"; }); print("Download completed"); }
可选方案与注意事项
- 如果你希望继续使用原
onProgress写法,可以将dio降级到4.0.6及之前版本,在pubspec.yaml中指定版本即可:dio: ^4.0.6 - 部分资源下载时不会返回
content-length响应头,此时total参数值为-1,需要额外做兼容处理避免出现除0异常 - 如需监听上传/请求发送的进度,可在
Options中配置onSendProgress回调
内容的提问来源于stack exchange,提问作者flu tter 87
相关产品推荐
相关产品推荐

