Flutter 下载文件操作

Flutter 下载文件操作
文章图片

原文

https://medium.com/halkbank-m...
代码 https://github.com/deremakif/...
参考
  • https://pub.dev/packages/path...
  • https://pub.dev/packages/flut...
  • https://pub.dev/packages/flowder
  • https://pub.dev/packages/open...
  • https://pub.dev/packages/perc...
正文 【Flutter 下载文件操作】今天我要写一篇关于 flowder package 的文章。我用它从服务器上下载文件。有很多方法可以做到这一点,而且还有更受欢迎的软件包如 flutter_downloader 。但我更喜欢 flowder 软件包,因为它的实现很简单。
首先,如果下载文件夹不存在,我们应该创建它。要做到这一点,我们需要导入 path_provider package。并在当前页的 initState() 中调用 initPlatformState 方法。
Future initPlatformState() async { _setPath(); if (!mounted) return; }void _setPath() async { Directory _path = await getApplicationDocumentsDirectory(); String _localPath = _path.path + Platform.pathSeparator + 'Download'; final savedDir = Directory(_localPath); bool hasExisted = await savedDir.exists(); if (!hasExisted) { savedDir.create(); } path = _localPath; }

现在,我们有下载文件夹来保存文件。包的下载方法需要两个参数: URL 和选项。您可以根据需要自定义选项。
ElevatedButton( onPressed: () async { options = DownloaderUtils( progressCallback: (current, total) { final progress = (current / total) * 100; print('Downloading: $progress'); }, file: File('$path/loremipsum.pdf'), progress: ProgressImplementation(), onDone: () { OpenFile.open('$path/loremipsum.pdf'); }, deleteOnCancel: true, ); core = await Flowder.download( "https://assets.website-files.com/603d0d2db8ec32ba7d44fffe/603d0e327eb2748c8ab1053f_loremipsum.pdf", options, ); },

我使用 OpenFile package 包在文件完成下载过程时打开它。我还使用了 percent_indicator package 包来显示进展。
如果以后不需要使用该文件,可以在关闭文档后删除该文件。重要的是不要增加应用程序的大小。
OpenFile.open('$path/loremipsum.pdf').then((value) { File f = File('$path/loremipsum.pdf'); f.delete(); });

  • 应用程序演示
Flutter 下载文件操作
文章图片

示例项目的源代码。
  • GitHub - deremakif/FlowderSample
    https://github.com/deremakif/...
? 猫哥
  • https://ducafecat.tech/
  • https://github.com/ducafecat
  • 微信群 ducafecat

    推荐阅读