Flutter文件下载插件simple_file_downloader_dart的使用

Flutter文件下载插件simple_file_downloader_dart的使用

特性

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

开始使用

首先,确保你已经在项目的pubspec.yaml文件中添加了simple_file_downloader_dart依赖。例如:

dependencies:
  simple_file_downloader_dart: ^x.x.x

然后运行flutter pub get来安装依赖。

初始化

在开始下载之前,可以进行一些初始化配置:

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

// 自定义dio(可选)
// FileDownloader.dio = Dio();

// 设置全局保存目录,必须设置,如果下载时不指定filePath
FileDownloader.globalSaveDir = "/Users/hss/Downloads";

下载文件

以下是一个简单的下载示例:

void main() {
  var url = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/WeAreGoingOnBullrun.mp4";

  FileDownloader(
    url: url,
    // filePath: "/Users/hss/Downloads/WeAreGoingOnBullrun-2.mp4",
    onSuccess: (String url, String filePath) {
      print('下载成功: $url -> $filePath');
    },
  ).start();
}

取消下载

如果你需要取消下载任务,可以使用FileDownloader.cancel方法:

Future.delayed(Duration(seconds: 3)).then((value) => FileDownloader.cancel(url));

配置项

FileDownloader构造函数支持以下配置项:

FileDownloader({
  required this.url,
  this.filePath,
  this.fileName,
  this.saveDir,
  this.forceRedownload,
  this.notAcceptRanges,
  this.headers = const {},
  this.fileSizeAlreadyKnown,
  this.onStartReal,
  this.onFailed,
  this.progressCallbackIntervalMills = 300,
  this.retryTimes = 1,
  this.tags = const {},
  required this.onSuccess,
  this.onProgress,
  this.onCancel,
})

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

1 回复

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


当然,下面是一个关于如何使用 simple_file_downloader_dart 插件在 Flutter 中进行文件下载的示例代码。这个插件允许你从网络下载文件并保存到设备的存储中。

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

dependencies:
  flutter:
    sdk: flutter
  simple_file_downloader_dart: ^最新版本号  # 请替换为最新版本号

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

接下来是完整的 Flutter 应用示例,展示如何使用 simple_file_downloader_dart 插件进行文件下载:

import 'package:flutter/material.dart';
import 'package:simple_file_downloader_dart/simple_file_downloader_dart.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'File Downloader Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late FileDownloader _downloader;
  late DownloadTaskStatus _downloadStatus;

  @override
  void initState() {
    super.initState();
    _downloader = FileDownloader();
    _downloadStatus = DownloadTaskStatus.idle;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('File Downloader Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () async {
                // 获取应用文档目录
                Directory appDocDir = await getApplicationDocumentsDirectory();
                String filePath = "${appDocDir.path}/example.zip";
                
                // 开始下载文件
                _downloader.downloadFile(
                  url: 'https://example.com/path/to/your/file.zip',
                  savedDir: appDocDir.path,
                  fileName: 'example.zip',
                  showNotification: true,
                  openFileFromNotification: true,
                  headers: {},
                ).listen(
                  (DownloadTaskStatus status) {
                    setState(() {
                      _downloadStatus = status;
                    });
                    print("Download status: ${status.toString()}");
                  },
                );
              },
              child: Text('Download File'),
            ),
            SizedBox(height: 20),
            Text('Download Status: $_downloadStatus'),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    // 取消所有下载任务(如果需要)
    _downloader.cancelAllDownloads();
    super.dispose();
  }
}

代码解释:

  1. 依赖添加:在 pubspec.yaml 中添加 simple_file_downloader_dart 依赖。

  2. 初始化:在 MyHomePageinitState 方法中初始化 FileDownloader 实例。

  3. 下载按钮:在 ElevatedButtononPressed 方法中,首先获取应用的文档目录,然后调用 _downloader.downloadFile 方法开始下载文件。

  4. 监听下载状态:使用 listen 方法监听下载状态的变化,并更新 UI 以显示当前的下载状态。

  5. 取消下载:在 dispose 方法中调用 _downloader.cancelAllDownloads() 方法取消所有下载任务(这是一个可选步骤,取决于你的需求)。

这个示例展示了如何使用 simple_file_downloader_dart 插件从指定的 URL 下载文件,并保存到设备的文档目录中。你可以根据需要进一步自定义和扩展这个示例。

回到顶部