解锁 Flutter
flutter_exit_app 库的鸿蒙适配解读,你离使用 Flutter 退出鸿蒙 app 只有一步之遥
适配仓库地址[1]
#鸿蒙坚果派 #鸿蒙版Flutter #鸿蒙开发者 #Flutter三方库
在数字化浪潮的推动下,跨平台开发框架如 Flutter 凭借其高效、便捷的特性,成为了开发者们的宠儿。而鸿蒙系统的崛起,更是为跨平台开发注入了新的活力。为了助力开发者在鸿蒙生态中快速实现 flutter_exit_app 退出应用程序功能,本文将深入浅出地为大家解析如何适配 flutter_exit_app 三方库至鸿蒙平台。
一、适配鸿蒙版 flutter_exit_app 三方库
(一)版本选择与仓库简介
我们先去 pub 上查看最新版本,发现目前 pub 上最新是 1.1.4,我们选择以 1.1.4 版本为基础进行适配。flutter_exit_app 是一个用于在 Flutter 应用中退出应用程序功能的插件,其 GitHub 仓库为 ,我们的目标是将这个插件适配到鸿蒙平台。
(二)引入背景与使用场景
在 OpenHarmony 北向生态的发展过程中,许多已经适配了 Flutter 的厂商在接入 OpenHarmony 时,都希望能够继续使用 FlutterToast 来实现通知功能。因此,我们提供了这个适配方案,采用插件化的适配器模式,帮助生态伙伴快速实现产品化。
本方案适用于已经支持 Flutter 框架的设备在移植到 OpenHarmony 系统过程中,作为一个备选方案。
(三)使用文档与插件库使用
适配 OpenHarmony 平台的详细使用指导可以参考:Flutter 使用指导文档[2]
在项目中使用该插件库时,只需在 pubspec.yaml
文件的 dependencies
中新增如下配置:
dependencies:
flutter_exit_app:
git:
url: ".git"
path: ""
然后在项目根目录运行 flutter pub get
,即可完成依赖添加
接下来是具体的适配过程。
二、适配过程详解
(一)准备工作
确保已经配置好了 Flutter 开发环境,具体可参考 Flutter 配置指南[3]。同时,从 官方插件库[4] 下载待适配的三方插件。本指导书, 以适配 fflutter_exit_app[5] 为例
image-20250417200546042
(二)插件目录结构
下载并解压插件后,我们会看到以下目录结构:
- lib :对接 Dart 端代码的入口,由此文件接收到参数后,通过 channel 将数据发送到原生端。
- android :安卓端代码实现目录。
- ios :iOS 原生端实现目录。
- example :一个依赖于该插件的 Flutter 应用程序,用于说明如何使用它。
- README.md :介绍包的文件。
- CHANGELOG.md :记录每个版本中的更改。
- LICENSE :包含软件包许可条款的文件。
(三)创建插件的鸿蒙模块
在插件目录下,打开 Terminal,执行以下命令来创建一个鸿蒙平台的 Flutter 模块:
代码语言:javascript代码运行次数:0运行复制flutter create . --template=plugin --platforms=ohos
步骤:
- 用 vscode/trae 打开刚刚下载好的插件。
- 打开 Terminal,cd 到插件目录下。
- 执行命令
flutter create . --template=plugin --platforms=ohos
创建一个 ohos 平台的 flutter 模块。
(四)在根目录下添加鸿蒙平台配置
在项目根目录的 pubspec.yaml
文件中,添加鸿蒙平台的相关配置:
name: flutter_exit_app
description:Aflutterpluginprovidesthebestwaytoexittheappdoesn'tcallexit(0)indartcode.
version:1.1.4
homepage:
environment:
sdk:">=2.14.0 <4.0.0"
flutter:">=2.5.0"
dependencies:
flutter:
sdk:flutter
dev_dependencies:
flutter_test:
sdk:flutter
lints:^3.0.0
test:
mockito:
build_runner:
# For information on the generic Dart part of this file, see the
# following page: /tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# This section identifies this Flutter project as a plugin project.
# The 'pluginClass' and Android 'package' identifiers should not ordinarily
# be modified. They are used by the tooling to maintain consistency when
# adding or updating assets for this project.
plugin:
platforms:
android:
package:com.laoitdev.lib.exit.app.flutter_exit_app
pluginClass:FlutterExitAppPlugin
ios:
pluginClass:FlutterExitAppPlugin
ohos:
package:com.laoitdev.lib.exit.app.flutter_exit_app
pluginClass:FlutterExitAppPlugin
# To add assets to your plugin package, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
#
# For details regarding assets in packages, see
# /assets-and-images/#from-packages
#
# An image asset can refer to one or more resolution-specific "variants", see
# /assets-and-images/#resolution-aware.
# To add custom fonts to your plugin package, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts in packages, see
# /custom-fonts/#from-packages
(五)编写鸿蒙插件的原生 ArkTS 模块
1. 创建鸿蒙插件模块
使用 DevEco Studio 打开鸿蒙项目。
2. 修改相关配置文件
在 ohos
目录内的 oh-package.json5
文件中添加 libs/flutter.har
依赖,并创建 .gitignore
文件,添加以下内容以忽略 libs
目录:
/node_modules
/oh_modules
/local.properties
/.preview
/.idea
/build
/libs
*.har
/.cxx
/.test
/BuildProfile.ets
/oh-package-lock.json5
oh-package.json5
文件内容如下:
{
"name": "flutter_exit_app",
"version": "1.0.0",
"description": "flutter plugin provides the best way to exit the app doesn't call exit(0) in dart code.",
"main": "index.ets",
"author": "nutpi",
"license": "Apache-2.0",
"dependencies": {
"@ohos/flutter_ohos": "file:./har/flutter.har"
},
"modelVersion": "5.0.4"
}
在 ohos
目录下创建 index.ets
文件,导出配置:
import FlutterExitAppPlugin from './src/main/ets/components/plugin/FlutterExitAppPlugin';
export default FlutterExitAppPlugin;
3. 编写 ETS 代码
文件结构和代码逻辑可以参考安卓或 iOS 的实现,鸿蒙的 API 文档可以参考 :
ohos 的 api 可以参考:
以下是 FlutterExitAppPlugin.ets
文件的代码示例:
import {
FlutterPlugin,
FlutterPluginBinding,
MethodCall,
MethodCallHandler,
MethodChannel,
MethodResult,
} from'@ohos/flutter_ohos';
import { AbilityAware, AbilityPluginBinding } from'@ohos/flutter_ohos';
import {common, UIAbility } from'@kit.AbilityKit';
import { BusinessError } from'@kit.BasicServicesKit';
/** FlutterExitAppPlugin **/
exportdefaultclass FlutterExitAppPlugin implements FlutterPlugin, MethodCallHandler , AbilityAware {
private channel: MethodChannel | null = null;
private static _context: Context | null = null;
private static _uiContext: common.UIAbilityContext | null = null;
constructor() {
}
staticget uiContext(): common.UIAbilityContext | null {
return FlutterExitAppPlugin._uiContext;
}
staticget context(): common.Context | null {
return FlutterExitAppPlugin._context;
}
get uiContext(): common.UIAbilityContext | null {
return FlutterExitAppPlugin._uiContext;
}
getUniqueClassName(): string {
return"FlutterExitAppPlugin"
}
onAttachedToAbility(binding: AbilityPluginBinding): void {
FlutterExitAppPlugin._uiContext = binding.getAbility().context;
// Called when the plugin is attached to an Ability.
}
onDetachedFromAbility(): void {
// this._uiContext = null;
}
onAttachedToEngine(binding: FlutterPluginBinding): void {
this.channel = new MethodChannel(binding.getBinaryMessenger(), "flutter_exit_app");
this.channel.setMethodCallHandler(this)
}
onDetachedFromEngine(binding: FlutterPluginBinding): void {
if (this.channel != null) {
this.channel.setMethodCallHandler(null)
}
}
onMethodCall(call: MethodCall, result: MethodResult): void {
if (call.method == "getPlatformVersion") {
result.success("OpenHarmony ^ ^ ")
} elseif (call.method == "com.laoitdev.exit.app") {
console.info("hhhhhhhhhh")
if (FlutterExitAppPlugin._uiContext) { // Add null check here
try {
FlutterExitAppPlugin._uiContext.terminateSelf()
.then(() => {
// 执行正常业务
console.info('terminateSelf succeed');
result.success("Done"); // Inform Flutter about success
})
.catch((err: BusinessError) => {
// 处理业务逻辑错误
console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
result.error("TERMINATE_FAILED", `terminateSelf failed: ${err.message}`, null);
});
} catch (err) {
// 捕获同步的参数错误
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`terminateSelf failed, code is ${code}, message is ${message}`);
result.error("TERMINATE_ERROR", `terminateSelf error: ${message}`, null);
}
} else {
console.error("UIContext is null, cannot terminate self.");
result.error("CONTEXT_NULL", "UIContext is null", null); // Inform Flutter about the error
}
} else {
result.notImplemented()
}
}
}
现在就可以正常使用啦。
这里我主要参考的是
4.UIAbilityContext.terminateSelf
代码语言:javascript代码运行次数:0运行复制import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export default class EntryAbility extends UIAbility {
onForeground() {
try {
this.context.terminateSelf()
.then(() => {
// 执行正常业务
console.info('terminateSelf succeed');
})
.catch((err: BusinessError) => {
// 处理业务逻辑错误
console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
// 捕获同步的参数错误
let code = (err as BusinessError).code;
let message = (err as BusinessError).message;
console.error(`terminateSelf failed, code is ${code}, message is ${message}`);
}
}
}
参考:
三、关于鸿蒙版 Flutter 的 context
这里我使用的是 UIAbilityContext
UIAbilityContext
插件继承 AbilityAware
并且在 onAttachedToAbility
方法中获取。
export default class XXXPlugin implements FlutterPlugin, MethodCallHandler, AbilityAware {
private _uiContext: common.UIAbilityContext | null = null;
onAttachedToAbility(binding: AbilityPluginBinding): void {
this.XXXPlugin = binding.getAbility().context;
}
onDetachedFromAbility(): void {
this.XXXPlugin = null;
}
}
该 uiContext
可以用于获取 applicationInfo
等属性。以及退出等操作。还有另外一种是
ApplicationContex
你可以直接从 onAttachedToEngine
方法中获取。
private context: Context | null = null;
onAttachedToEngine(binding: FlutterPluginBinding): void {
this.context = binding.getApplicationContext();
}
onDetachedFromEngine(binding: FlutterPluginBinding): void {
this.context = null;
}
该 context
可以用于获取 applicationInfo
等属性。
let applicationInfo = this.context.applicationInfo;
四、编写 Example
1. 创建 Example 应用
在插件根目录下创建一个名为 example
的文件夹,用于存放示例应用。在 example
文件夹中,创建一个鸿蒙平台的 Flutter 应用,用于验证插件功能。
2. 签名与运行
使用 Deveco Studio
打开 example > ohos
目录,单击 File > Project Structure > Project > Signing Configs
,勾选 Automatically generate signature
,等待自动签名完成。然后运行以下命令:
flutter pub get
flutter build hap --debug
如果应用正常启动,说明插件适配成功。如果没有,欢迎大家联系坚果派一起支持。
五、总结
通过以上步骤,我们成功地将 flutter_exit_app 三方库适配到了鸿蒙平台。这个过程涉及到了解插件的基本信息、配置开发环境、创建鸿蒙模块、编写原生代码以及测试验证等多个环节。希望这篇博客能够帮助到需要进行 flutter_exit_app 鸿蒙适配的开发者们,让大家在鸿蒙生态的开发中更加得心应手。
六、参考
- [如何使用 Flutter 与 OpenHarmony 通信 FlutterChannel]( FlutterChannel.md "如何使用 Flutter 与 OpenHarmony 通信 FlutterChannel")
- [开发 module]( module.md "开发 module")
- 开发 package[6]
- 开发 plugin[7]
- [开发 FFI plugin]( plugin.md "开发 FFI plugin")
- developing-packages[8]
- 适配仓库地址[9]
参考资料
[1]
适配仓库地址:
[2]
Flutter 使用指导文档: .md
[3]
Flutter 配置指南: .md
[4]
官方插件库: /
[5]
fflutter_exit_app: .1.4
[6]
开发 package: .md
[7]
开发 plugin: .md
[8]
developing-packages:
[9]
适配仓库地址:
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。原始发表:2025-04-29,如有侵权请联系 cloudcommunity@tencent 删除exit插件开发flutterapp