Flutter 3.35 For HarmonyOS 如何正确的使用第三方库
一、问题现象
在使用 Flutter 3.35 OHOS 分支开发 HarmonyOS 应用时,执行:
flutter run
构建 HAP 阶段报错:
hvigor ERROR: AdaptorError 00303231 Configuration Error
Error Message: The srcPath is not a relative path:
C:/Users/xxx/AppData/Local/Pub/Cache/git/flutter_packages-xxxx/packages/shared_preferences/shared_preferences_ohos/ohos
核心报错:
The srcPath is not a relative path
二、问题本质
HarmonyOS 使用的是来自 OpenHarmony 生态的 Hvigor 构建系统。
Hvigor 有一个硬性要求:
srcPath 必须是相对路径
不允许使用绝对路径
而当我们使用 git 依赖时,例如:
shared_preferences:
git:
url: "https://gitcode.com/openharmony-tpc/flutter_packages.git"
path: "packages/shared_preferences/shared_preferences"
Flutter 会把插件 clone 到:
C:/Users/xxx/AppData/Local/Pub/Cache/git/flutter_packages-xxxx/
这是绝对路径。
Harmony Flutter 适配层在生成 hvigorconfig.ts 时,会把这个绝对路径写进去,最终导致构建失败。
三、很多人忽略的关键点
即便你把项目依赖改成:
shared_preferences:
path: packages/shared_preferences/shared_preferences
仍然可能报错。
原因是:
插件内部的 shared_preferences/pubspec.yaml 里,默认依然是:
shared_preferences_ohos:
git:
url: https://gitee.com/openharmony-sig/flutter_packages.git
也就是说:
你的项目
↓
shared_preferences(path)
↓
shared_preferences_ohos(git ❌)
内部依然会从 Pub Cache 读取 git 插件,最终触发 hvigor 绝对路径错误。
四、packages/shared_preferences/shared_preferences 从哪里来?
这是很多人最疑惑的地方。
有两种获取方式:
✅ 方式一(推荐):直接从 Pub Cache 拷贝
当你曾经使用过 git 方式后,Flutter 已经把插件下载到了本地:
C:/Users/xxx/AppData/Local/Pub/Cache/git/flutter_packages-xxxx/
进入:
C:/Users/xxx/AppData/Local/Pub/Cache/git/flutter_packages-xxxx/packages/shared_preferences/
你会看到:
shared_preferences/
shared_preferences_ohos/
shared_preferences_android/
把整个 shared_preferences 文件夹复制到你的项目中,例如:
项目名/
└── packages/
└── shared_preferences/
├── shared_preferences/
├── shared_preferences_ohos/
├── shared_preferences_android/
注意:
必须复制的是这一整层:
packages/shared_preferences/
不能只复制最里面那一层。
✅ 方式二:从插件仓库克隆
也可以直接从 OpenHarmony TPC 的 flutter 插件仓库克隆:
git clone https://gitcode.com/openharmony-tpc/flutter_packages.git
然后从:
flutter_packages/packages/shared_preferences/
拷贝到项目的 packages/ 目录中。
五、正确的项目结构
最终你的项目结构应该是:
项目名/
│
├── pubspec.yaml
├── lib/
└── packages/
└── shared_preferences/
├── shared_preferences/
│ └── pubspec.yaml
├── shared_preferences_ohos/
├── shared_preferences_android/
六、必须修改插件内部依赖
打开:
packages/shared_preferences/shared_preferences/pubspec.yaml
把:
shared_preferences_ohos:
git:
url: https://gitee.com/openharmony-sig/flutter_packages.git
改成:
shared_preferences_ohos:
path: ../shared_preferences_ohos
否则仍然会走 git。
七、修改项目依赖
在项目根 pubspec.yaml 中:
shared_preferences:
path: packages/shared_preferences/shared_preferences
八、彻底清理缓存(非常关键)
flutter clean
然后手动删除:
.dart_tool
build
pubspec.lock
ohos/.hvigor
再执行:
flutter pub get
flutter run
九、验证是否成功
打开 pubspec.lock,确认:
shared_preferences_ohos:
source: path
绝对不能再是 git。
十、最终结论
HarmonyOS Flutter 当前阶段的铁律:
所有 OHOS 插件必须放在工程目录内
所有依赖必须使用 path 相对路径
不能使用 git 依赖
否则 100% 会触发 hvigor srcPath 绝对路径错误。
如果你正在做 HarmonyOS + Flutter 开发,这个坑几乎必踩。
希望这篇文章能帮你节省几个小时的排查时间。
更多推荐


所有评论(0)