Flutter 3.47 鸿蒙三方库适配实战:从 0 到 1 处理 native_file_preview

调用系统默认应用预览沙箱内的文件。

本文以 native_file_preview 1.1.0 为例,记录我如何保留原有 Dart API、补齐 Flutter OH 插件入口、在鸿蒙端接入真实系统能力,并在 HarmonyOS API 26 真机上完成构建、安装、启动与调用验证。

适配仓库: native_file_preview

适配分支: feat/ohos_native_file_preview_1.1.0

适配 TAG: 1.1.0-ohos.1

一、先看最终效果

在这里插入图片描述

图 1:HarmonyOS API 26 真机启动示例页

验证点实测结果
Flutter OH 3.47 工程构建通过,产出 entry-default-signed.hap
安装、启动(真机)通过
插件注册通道 native_file_preview 就绪
调用 previewFile拉起系统预览应用

二、这个库原来是怎么工作的

上游 native_file_preview 通过平台通道与原生侧通信,通道定义在 Dart 源码里,原生侧只需要注册同名通道并实现方法分发,Dart 代码一行都不用改。

MethodChannel('native_file_preview')
  -> getPlatformVersion / previewFile

三、实际环境

Flutter 鸿蒙环境搭建不在本文重复展开,直接参考 Flutter OH 环境搭建指南。

组件版本
Flutter OH3.47.4-ohos-1.0.4
Dart3.13.3
DevEco Studio26.0.0 Release
HarmonyOS SDKAPI 26
测试设备华为畅享 90 Pro Max(CHZ-AL00),HarmonyOS 7.0.0.109(API 26)
目标库native_file_preview 1.1.0
flutter --version
hdc list targets

这里要特别注意 Flutter 版本:本机同时装了 3.41 和 3.47.4-ohos,3.41 会因为 SDK 约束解析失败,构建时必须显式把 3.47.4-ohos 放到 PATH 前面。

四、确认上游版本并同步到 AtomGit

上游包地址是 https://github.com/johnny-bytes/native_file_preview,版本 1.1.0 使用 MIT License。适配前我用 AtomGit API(GET /api/v5/repos/<org>/<lib>)在 oh-flutter、hxa-flutter、CPF-Flutter 三个组织做了排重,未发现同名 OHOS 实现。

git clone https://atomgit.com/oh-flutter/native_file_preview.git
cd native_file_preview
git switch feat/ohos_native_file_preview_1.1.0
git log --oneline -5

五、创建适配分支并检查工程结构

git switch -c feat/ohos_native_file_preview_1.1.0

关键目录如下:

native_file_preview/
├── lib/                                         # 原有 Dart API 和通道
├── ohos/
│   ├── index.ets                                # OHOS 插件导出入口
│   └── src/main/ets/components/plugin/
│       └── NativeFilePreviewPlugin.ets
├── example/lib/main.dart                        # 真机验证 Demo
├── example/ohos/                                # Flutter OH 宿主工程
├── pubspec.yaml                                 # 声明 ohos 平台
└── README.OpenHarmony_CN.md                     # 鸿蒙适配说明
flutter:
  plugin:
    platforms:
      ohos:
        pluginClass: NativeFilePreviewPlugin

pluginClass 必须和 ohos/index.ets 导出的类名一致。这一步是本批次最容易踩的坑:pubspec.yaml 里漏掉 ohos 声明时,Flutter 生成的 GeneratedPluginRegistrant.ets 是个空 try 块,Dart 侧调用直接返回 null,构建期没有任何报错,运行时也不抛 MissingPluginException,只是所有返回值都是空的。我第一次跑 is_lock_screen2 就卡在这里,查了半天日志才发现注册表是空的。

六、适配过程:注册通道并对齐语义

通道名必须与上游 Dart 源码逐字一致。本库的映射如下:

方法OpenHarmony 实现说明
previewFile`startAbility({action: ohos.want.action.viewData, uri: file://yes
getPlatformVersion返回平台标识yes

核心代码:

    if (call.method === 'getPlatformVersion') {
      result.success('OpenHarmony');
      return;
    }
    if (call.method !== 'previewFile') {
      result.notImplemented();
      return;
    }
    const file: string = call.argument('file') ?? '';
    const ctx = this.ctx;
    if (!file) {
      result.error('INVALID_ARGS', 'file path is required', null);
      return;
    }
    if (ctx === null) {
      result.error('NO_CONTEXT', 'ability context is unavailable', null);
      return;
    }
    const uri: string = 'file://' + ctx.applicationInfo.name + file;
    ctx.startAbility({
      action: 'ohos.want.action.viewData',
      uri: uri

七、构建配置与签名

示例工程的目标 SDK 对齐到 26,与 @ohos/flutter_ohos 的要求一致:

{
  "name": "default",
  "compatibleSdkVersion": "26.0.0",
  "targetSdkVersion": "26.0.0",
  "runtimeOS": "HarmonyOS"
}

Demo 的 AppScope/app.json5 统一成 com.example.flutter_oh_demo。签名 profile 里绑定的 bundleName 必须与它一致,否则 SignHap 直接报 00303074 Configuration Error。证书、p12、p7b 和密码不提交到仓库。

另外两个和签名、SDK 相关的坑:

  • build-profile.json5 里签名材料写 ${HOME} 不会展开,必须是绝对路径,否则报 00303107 Invalid storeFile value。
  • DEVECO_SDK_HOME 要指向 Contents/sdk(含版本目录的上一级)。指到 sdk/default 报 00303312 Cannot find the corresponding SDK version,完全不设则报 00303217。

八、通过 AtomGit 引入适配版

在业务工程中使用时锁定 TAG:

dependencies:
  native_file_preview:
    git:
      url: https://atomgit.com/oh-flutter/native_file_preview.git
      ref: 1.1.0-ohos.1
flutter pub get

然后在 pubspec.lock 里确认 source: git、AtomGit 地址和 resolved-ref,避免解析到 pub.dev 的同名版本。

九、构建、安装和真机验证

cd example
flutter pub get
flutter build hap --debug
hdc install -r build/ohos/hap/entry-default-signed.hap
hdc shell aa start -a EntryAbility -b com.example.flutter_oh_demo

构建输出为 ✓ Built build/ohos/hap/entry-default-signed.hap.,随后 hdc 报告安装成功。所有示例共用同一个 bundleName,重装后要先 aa force-stop 再 aa start,否则系统只是把旧任务拉到前台,看到的是上一次安装的界面——这个现象在批量验证时骗过我一次。

取实测值时用 uitest 定位控件并点击,而不是靠肉眼判断:

hdc shell "uitest dumpLayout -p /data/local/tmp/l.json"
hdc file recv /data/local/tmp/l.json /tmp/l.json
hdc shell "uitest uiInput click <x> <y>"
hdc shell "uitest screenCap -p /data/local/tmp/s.png"

十、适配结果和当前边界

  • 只处理应用沙箱内的路径。跨应用文件需要走文件分享授权(fileUri + 临时授权),本实现未覆盖。
  • 预览应用由系统按 MIME 类型选择,若设备上没有能打开该类型的应用,startAbility 会失败并返回 PREVIEW_FAILED。

十一、FAQ

Q1:为什么沙箱外的文件打不开?

  • 原因: 实现只处理应用沙箱内路径,URI 形如 file://<bundleName>/<沙箱路径>。跨应用文件需要走文件分享授权(fileUri + 临时授权),本实现未覆盖。

Q2:什么时候会报 PREVIEW_FAILED?

  • 原因: 系统按类型选择预览应用,若设备上没有能打开该类型的应用,startAbility 失败并返回这个错误码,不会静默成功。

Q3:bundleName 是硬编码的吗?

  • 原因: 不是。从 UIAbilityContext.applicationInfo.name 取,保证 URI 里的包名与应用实际包名一致。

十二、总结

native_file_preview 1.1.0 在鸿蒙上已经接入真实系统能力,Dart 侧 API 与上游保持一致。本文的验证结果全部来自 HarmonyOS API 26 真机,没有占位返回值;平台本身不具备的能力在正文和 README 中都标注为边界。

十三、参考资料和仓库地址

欢迎加入CPF-Flutter 鸿蒙社区:https://atomgit.com/CPF-Flutter

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐