Flutter dio下载文件
时间: 2025-05-04 18:41:09 浏览: 31
### 如何使用 Flutter 的 Dio 插件实现文件下载功能
在 Flutter 中,`dio` 是一个非常流行的 HTTP 请求库,它提供了许多高级功能,其中包括文件下载的支持。以下是关于如何通过 `dio` 实现文件下载的具体方法。
#### 依赖配置
首先,在项目的 `pubspec.yaml` 文件中添加必要的依赖项:
```yaml
dependencies:
dio: ^5.1.1
```
完成上述操作后,请运行命令 `flutter pub get` 来安装所需的包[^3]。
#### 创建 Dart 文件并初始化 Dio 对象
创建一个新的 Dart 文件用于处理网络请求逻辑,并初始化 `Dio` 类实例:
```dart
import 'package:dio/dio.dart';
class FileDownloader {
final Dio _dio = Dio(); // 初始化 Dio 实例
Future<void> downloadFile(String url, String savePath) async {
try {
await _dio.download(
url,
savePath,
onReceiveProgress: (receivedBytes, totalBytes) {
if (totalBytes != -1) {
print('Download progress: ${(receivedBytes / totalBytes * 100).toStringAsFixed(0)}%');
}
},
);
print('File downloaded successfully at $savePath.');
} catch (e) {
print('Error during file download: $e');
}
}
}
```
此代码片段展示了如何利用 `download()` 方法执行文件下载任务。参数说明如下:
- **url**: 要下载的目标资源 URL 地址。
- **savePath**: 将要保存到本地设备上的路径。
- **onReceiveProgress**: 可选回调函数,用于实时监控下载进度[^4]。
#### 使用示例
下面是如何调用上面定义的方法的一个简单例子:
```dart
void main() async {
var downloader = FileDownloader();
const String fileUrl =
'https://example.com/sample.pdf'; // 替换为实际的远程文件链接
const String localSavePath =
'/storage/emulated/0/Download/example.pdf'; // Android 设备存储位置
await downloader.downloadFile(fileUrl, localSavePath);
}
```
注意:对于 iOS 和某些版本的 Android 应用程序来说,可能还需要额外设置权限以及指定合适的目录结构才能成功写入数据。
#### 处理异常情况
当遇到错误时(例如网络中断或者服务器返回非预期状态码),可以通过捕获异常来进行相应的处理[^2]:
```dart
try {
...
} on DioException catch (e) {
switch (e.type) {
case DioExceptionType.connectionTimeout:
print('Connection timed out');
break;
default:
print('An unexpected error occurred: ${e.message}');
}
}
```
以上就是基于 Flutter 平台下借助于 dio 插件完成文件下载的核心流程介绍[^1]。
---
阅读全文
相关推荐


















