如何在Flutter中下载PDF并保存至iOS下载文件夹使其显示在最近文件中
Flutter iOS 实现PDF下载到「下载」文件夹并显示在Files「最近」栏
需要用到的依赖
直接在pubspec.yaml里添加以下包:
dependencies: flutter: sdk: flutter dio: ^5.4.0 # 处理文件下载,自带进度回调,比基础http包更实用 path_provider: ^2.1.2 # 快速获取系统标准目录路径
iOS项目必须配置的两项
1. Info.plist添加文件权限
打开iOS项目的Info.plist(Xcode里右键选择Open As -> Source Code),插入以下代码片段:
<key>LSSupportsOpeningDocumentsInPlace</key> <true/> <key>UIFileSharingEnabled</key> <true/>
UIFileSharingEnabled:让应用被Files应用识别,开启文件共享能力LSSupportsOpeningDocumentsInPlace:确保文件直接出现在Files的「最近」栏目,无需额外移动操作
2. 选择正确的存储目录
别用getApplicationDocumentsDirectory,这个是应用私有目录,Files应用无法访问。必须用getDownloadsDirectory,它会直接指向iOS系统的「下载」文件夹。
下载并保存PDF的核心代码
import 'dart:io'; import 'package:dio/dio.dart'; import 'package:path_provider/path_provider.dart'; Future<void> downloadAndSavePdf(String pdfUrl, String fileName) async { try { // 获取系统下载目录 final downloadsDir = await getDownloadsDirectory(); if (downloadsDir == null) { throw "无法获取系统下载目录"; } // 拼接文件路径,加时间戳避免覆盖已有文件 final savePath = '${downloadsDir.path}/${fileName}_${DateTime.now().millisecondsSinceEpoch}.pdf'; // 发起下载请求 final dio = Dio(); await dio.download( pdfUrl, savePath, onReceiveProgress: (received, total) { if (total != -1) { // 这里可以更新UI展示下载进度 print('下载进度: ${(received / total * 100).floor()}%'); } }, ); // 关键操作:通知iOS系统刷新文件索引,否则Files看不到新文件 if (Platform.isIOS) { // 模拟器用这个命令触发刷新 await Process.run('xcrun', ['simctl', 'addmedia', 'booted', savePath]); // 真机可调用原生Swift/OC代码,或者用flutter_file_system这类插件简化刷新逻辑 } print('PDF已保存至: $savePath'); } catch (e) { print('下载失败: $e'); } }
踩坑提醒
- 文件刷新:iOS不会自动扫描新增文件,必须手动触发索引刷新,不然Files的「最近」栏不会显示刚下载的PDF。
- 文件名唯一性:一定要给文件名加唯一标识(比如时间戳、UUID),否则会直接覆盖同名文件。
- 权限处理:iOS 13+首次访问文件系统会弹出权限请求,要提前处理用户拒绝的情况,比如引导用户去设置开启权限。
内容的提问来源于stack exchange,提问作者Ragul PR
相关产品推荐
相关产品推荐

