Flutter macOS桌面应用:如何获取应用包Resources文件夹路径?
如何获取应用Resources文件夹路径?
开发时能用相对路径访问,但生产环境失效,核心原因是应用打包成.app包后,工作目录和项目根目录完全不同,必须通过系统提供的API来获取Resources的正确路径,分两种场景解决:
Flutter项目
- 先添加
path_provider依赖到pubspec.yaml,再通过以下代码获取Resources目录:
import 'package:path_provider/path_provider.dart'; Future<String> getResourcesDir() async { // 拿到对应macOS下Contents/Resources的目录路径 final dir = await getApplicationSupportDirectory(); return dir.path; }
- 如果你是把
html文件夹作为静态资源打包进应用,别手动拼接路径,直接在pubspec.yaml里声明资源:
assets: - html/
然后用Flutter自带的资源加载方法直接读取内容:
import 'package:flutter/services.dart'; final htmlContent = await rootBundle.loadString('html/index.html');
原生macOS项目
Swift 实现
if let resourcesPath = Bundle.main.resourcePath { let htmlFolderPath = URL(fileURLWithPath: resourcesPath).appendingPathComponent("html") // 用htmlFolderPath访问目标文件夹 }
Objective-C 实现
NSString *resourcesPath = [[NSBundle mainBundle] resourcePath]; NSURL *htmlFolderPath = [NSURL fileURLWithPath:resourcesPath].URLByAppendingPathComponent:@"html";
关键提醒
开发环境下Directory('html')能生效,是因为当前工作目录就是项目根目录,但生产环境中.app包的运行目录和开发时完全不同,必须通过Bundle相关API获取Resources的绝对路径,不能依赖相对路径。
内容的提问来源于stack exchange,提问作者Harald Schneider
相关产品推荐
相关产品推荐

