Flutter文件下载管理插件simple_file_downloader_flutter的使用

发布于 1周前 作者 zlyuanteng 来自 Flutter

Flutter文件下载管理插件simple_file_downloader_flutter的使用

Features

  • 纯Dart实现
  • 支持断点续传
  • 支持进度和速度回调

Getting started

在开始使用simple_file_downloader_flutter之前,确保你已经在项目的pubspec.yaml文件中添加了该插件的依赖:

dependencies:
  simple_file_downloader_flutter: ^版本号

然后运行以下命令来安装依赖:

flutter pub get

Usage

以下是一个简单的使用示例:

// 初始化
// 打开日志,默认关闭
FileDownloader.openLog = true;

// 自定义Dio实例(非必要)
// FileDownloader.dio = Dio();

// 设置默认的下载保存目录,如果在下载时不指定filePath,则必须设置此值
FileDownloader.globalSaveDir = "/Users/hss/Downloads";

// 下载URL
var url = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/WeAreGoingOnBullrun.mp4";

// 开始下载
FileDownloader(
  url: url,
  // 可选参数:filePath(指定文件保存路径),forceRedownload等
  onSuccess: (String url, String filePath) {
    print('下载成功: $url -> $filePath');
  },
).start();

// 取消下载
Future.delayed(Duration(seconds: 3)).then((value) => FileDownloader.cancel(url));

配置参数

FileDownloader支持多种配置参数,以下是一些常用的参数:

FileDownloader({
  required this.url, // 必填,下载的URL
  this.filePath, // 可选,指定文件保存路径
  this.forceRedownload = false, // 是否强制重新下载
  this.notAcceptRanges = false, // 是否忽略断点续传
  this.headers = const {}, // HTTP请求头
  this.fileSizeAlreadyKnown = false, // 文件大小是否已知
  this.onStartReal, // 下载开始时的回调
  this.onFailed, // 下载失败时的回调
  this.progressCallbackIntervalMills = 300, // 进度回调间隔时间(毫秒)
  this.retryTimes = 1, // 重试次数
  this.tags = const {}, // 标签
  required this.onSuccess, // 下载成功时的回调
  this.onProgress, // 进度更新时的回调
  this.onCancel, // 下载取消时的回调
});

更多关于Flutter文件下载管理插件simple_file_downloader_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter文件下载管理插件simple_file_downloader_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


simple_file_downloader_flutter 是一个用于在 Flutter 应用中下载文件的简单插件。它提供了基本的文件下载功能,并且易于集成和使用。以下是如何在 Flutter 项目中使用 simple_file_downloader_flutter 插件的步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 simple_file_downloader_flutter 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  simple_file_downloader_flutter: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来获取依赖。

2. 导入插件

在你的 Dart 文件中导入插件:

import 'package:simple_file_downloader_flutter/simple_file_downloader_flutter.dart';

3. 下载文件

使用 SimpleFileDownloaderFlutter 提供的 downloadFile 方法来下载文件。以下是一个简单的示例:

void downloadFile() async {
  String url = 'https://example.com/path/to/your/file.zip';
  String fileName = 'file.zip';

  try {
    String? filePath = await SimpleFileDownloaderFlutter.downloadFile(
      url: url,
      fileName: fileName,
    );

    if (filePath != null) {
      print('File downloaded to: $filePath');
    } else {
      print('Download failed');
    }
  } catch (e) {
    print('Error downloading file: $e');
  }
}

4. 处理下载进度(可选)

如果你需要显示下载进度,可以使用 downloadFileWithProgress 方法:

void downloadFileWithProgress() async {
  String url = 'https://example.com/path/to/your/file.zip';
  String fileName = 'file.zip';

  try {
    String? filePath = await SimpleFileDownloaderFlutter.downloadFileWithProgress(
      url: url,
      fileName: fileName,
      onProgress: (double progress) {
        print('Download progress: ${(progress * 100).toStringAsFixed(2)}%');
      },
    );

    if (filePath != null) {
      print('File downloaded to: $filePath');
    } else {
      print('Download failed');
    }
  } catch (e) {
    print('Error downloading file: $e');
  }
}

5. 处理下载路径(可选)

默认情况下,文件会下载到应用的缓存目录。你可以通过 downloadDirectory 参数指定自定义的下载目录:

void downloadFileToCustomDirectory() async {
  String url = 'https://example.com/path/to/your/file.zip';
  String fileName = 'file.zip';
  String customDirectory = '/storage/emulated/0/Download';

  try {
    String? filePath = await SimpleFileDownloaderFlutter.downloadFile(
      url: url,
      fileName: fileName,
      downloadDirectory: customDirectory,
    );

    if (filePath != null) {
      print('File downloaded to: $filePath');
    } else {
      print('Download failed');
    }
  } catch (e) {
    print('Error downloading file: $e');
  }
}

6. 处理权限(Android)

在 Android 上,你可能需要请求存储权限才能将文件保存到外部存储。你可以使用 permission_handler 插件来请求权限:

dependencies:
  permission_handler: ^10.0.0  # 请使用最新版本

然后在代码中请求权限:

import 'package:permission_handler/permission_handler.dart';

void requestPermissions() async {
  if (await Permission.storage.request().isGranted) {
    print('Storage permission granted');
  } else {
    print('Storage permission denied');
  }
}

7. 处理 iOS 配置(可选)

在 iOS 上,你可能需要在 Info.plist 文件中添加以下配置以允许下载文件:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!