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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 20:30:00