flutter如何实现文件下载

我在Flutter项目中需要实现文件下载功能,但不太清楚具体该怎么操作。目前遇到几个问题:1. 应该使用什么插件或库来实现下载?2. 如何显示下载进度条?3. 下载的文件应该保存在什么目录?4. 如何处理下载过程中的网络异常和权限问题?希望能得到详细的实现方案和代码示例。

2 回复

Flutter中可使用dio库实现文件下载。步骤如下:

  1. 添加dio依赖到pubspec.yaml
  2. 创建Dio实例并调用download方法,指定URL和保存路径。
  3. 可选:监听下载进度或处理异常。

示例代码:

await dio.download(url, savePath, onReceiveProgress: (received, total) {
  // 更新进度
});

更多关于flutter如何实现文件下载的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中实现文件下载,可以使用dio库(推荐)或http库结合文件操作。以下是完整实现方案:

1. 添加依赖

dependencies:
  dio: ^5.0.0
  path_provider: ^2.0.0
  permission_handler: ^11.0.0 # 用于权限处理

2. 核心下载代码

import 'dart:io';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';

class DownloadService {
  static Future<String?> downloadFile({
    required String url,
    required String fileName,
    Function(int, int)? onProgress,
  }) async {
    try {
      // 获取下载目录
      Directory? downloadsDir = await getExternalStorageDirectory();
      if (downloadsDir == null) {
        downloadsDir = await getApplicationDocumentsDirectory();
      }
      
      String savePath = '${downloadsDir.path}/$fileName';
      
      // 使用dio下载
      Dio dio = Dio();
      await dio.download(
        url,
        savePath,
        onReceiveProgress: onProgress,
      );
      
      return savePath;
    } catch (e) {
      print('下载失败: $e');
      return null;
    }
  }
}

3. 在UI中使用

class DownloadPage extends StatefulWidget {
  @override
  _DownloadPageState createState() => _DownloadPageState();
}

class _DownloadPageState extends State<DownloadPage> {
  double _progress = 0;
  bool _isDownloading = false;

  void _startDownload() async {
    setState(() {
      _isDownloading = true;
      _progress = 0;
    });

    String? filePath = await DownloadService.downloadFile(
      url: 'https://example.com/file.pdf',
      fileName: 'document.pdf',
      onProgress: (received, total) {
        if (total != -1) {
          setState(() {
            _progress = received / total;
          });
        }
      },
    );

    setState(() {
      _isDownloading = false;
    });

    if (filePath != null) {
      // 下载成功
      print('文件保存路径: $filePath');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (_isDownloading)
              LinearProgressIndicator(value: _progress),
            ElevatedButton(
              onPressed: _isDownloading ? null : _startDownload,
              child: Text(_isDownloading ? '下载中...' : '开始下载'),
            ),
          ],
        ),
      ),
    );
  }
}

4. 权限处理(Android)

android/app/src/main/AndroidManifest.xml 中添加:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

关键点说明:

  • dio:强大的HTTP客户端,支持文件下载和进度回调
  • path_provider:获取设备存储路径
  • 权限处理:Android需要存储权限
  • 进度显示:通过onReceiveProgress回调更新UI

这种方法支持大文件下载、进度显示和错误处理,是Flutter文件下载的常用方案。

回到顶部