HarmonyOS鸿蒙Next中flutter与原生ArkTs交互示例
HarmonyOS鸿蒙Next中flutter与原生ArkTs交互示例
Flutter与原生ArkTS交互实现
介绍
在适配HarmonyOS的Flutter框架创建项目时,系统会在ohos/entry/src/main/ets/entryability
目录下生成一个继承于FlutterAbility
的EntryAbility
。
该文件中包含一个初始化的configureFlutterEngine
函数,可用于实现Flutter与ArkTS的方法交互。在该函数中,通过MethodCallHandler
监听Flutter向原生发送的请求,并返回应答。
Flutter与ArkTS交互流程
1. 原生侧交互添加方法监听
在configureFlutterEngine
函数中,配置MethodChannel
,并通过setMethodCallHandler
监听Flutter发送的请求:
import { FlutterAbility, FlutterEngine, MethodChannel, MethodCall, MethodResult } from '@ohos/flutter_ohos';
export default class EntryAbility extends FlutterAbility {
configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine);
const methodChannel = new MethodChannel(flutterEngine.dartExecutor, "com.example.channel");
methodChannel.setMethodCallHandler({
onMethodCall: async (call: MethodCall, result: MethodResult) => {
if (call.method === 'getNativeData') {
this.getNativeData()
.then(data => result.success(data))
.catch(() => result.error("500", 'Internal error', null));
} else {
result.error("404", 'Method not found', null);
}
},
});
}
async getNativeData() {
return {
message: 'Hello from ArkTS',
timestamp: Date.now(),
};
}
}
2. Flutter侧交互调用
在Flutter侧,通过MethodChannel
调用ArkTS端方法:
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
class NativeInteractionPage extends StatelessWidget {
final MethodChannel _channel = MethodChannel('com.example.channel');
Future<Map<String, dynamic>> _getNativeData() async {
try {
final result = await _channel.invokeMethod('getNativeData');
return Map<String, dynamic>.from(result);
} catch (e) {
throw 'Failed to get native data: $e';
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter-ArkTS Interaction'),
),
body: Center(
child: FutureBuilder<Map<String, dynamic>>(
future: _getNativeData(), // 获取数据
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator(); // 显示加载动画
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else if (snapshot.hasData) {
final data = snapshot.data!;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Message: ${data['message']}'),
Text('Timestamp: ${data['timestamp']}'),
],
);
} else {
return Text('No data received');
}
},
),
),
);
}
}
进阶使用
异步数据处理
在一些复杂场景中,ArkTS可以异步处理任务并将结果返回给Flutter,避免阻塞主线程。
ArkTS端实现
import { FlutterAbility, FlutterEngine, MethodChannel, MethodCall, MethodResult, Any } from '@ohos/flutter_ohos';
export default class EntryAbility extends FlutterAbility {
configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine);
const methodChannel = new MethodChannel(flutterEngine.dartExecutor, "com.example.channel");
methodChannel.setMethodCallHandler({
onMethodCall: async (call: MethodCall, result: MethodResult) => {
if (call.method === 'performLongTask') {
this.performLongTask(call.args)
.then(data => result.success(data))
.catch(() => result.error("500", 'Task failed', null));
} else {
result.error("404", 'Method not found', null);
}
},
});
}
async performLongTask(args: Any): Promise<string> {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (args?.success) {
resolve('Task completed');
} else {
reject({ error: 'Task failed', reason: 'Invalid input' });
}
}, 2000);
});
}
}
Flutter端实现
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
class LongTaskPage extends StatelessWidget {
final MethodChannel _channel = MethodChannel('com.example.channel');
Future<void> _performLongTask() async {
try {
final result = await _channel.invokeMethod('performLongTask', {'success': true});
print('Task Result: $result');
} catch (error) {
print('Task Failed: $error');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Perform Long Task'),
),
body: Center(
child: ElevatedButton(
onPressed: _performLongTask,
child: Text('Start Long Task'),
),
),
);
}
}
注意事项
-
命名规范
- Flutter侧使用的
method
、MethodChannel
名称与ArkTS端定义的名称必须一致,避免重复命名。
- Flutter侧使用的
-
鸿蒙原生端
- 通过configureFlutterEngine配置监听器,并根据请求的method执行选择的功能。
-
Flutter端
- 使用invokeMethod调用ArkTS方法,并通过await或异步的方式进行对应数据的处理。
- Flutter中调用二方交互方法时,需根据需要处理对应的返回数据。
通过上述方法,可以完成Flutter与ArkTS的交互,从而实现原生功能与Flutter应用的深度融合。
更多关于HarmonyOS鸿蒙Next中flutter与原生ArkTs交互示例的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
好文,先收藏!
更多关于HarmonyOS鸿蒙Next中flutter与原生ArkTs交互示例的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在HarmonyOS鸿蒙Next中,Flutter与原生ArkTS的交互可以通过平台通道(Platform Channel)实现。Flutter提供了MethodChannel
用于与原生代码进行通信。以下是一个简单的示例,展示如何在Flutter中调用ArkTS的方法,并获取返回值。
- Flutter端代码:
import 'package:flutter/services.dart';
class NativeBridge {
static const platform = MethodChannel('com.example.flutter/native');
Future<String> getNativeMessage() async {
try {
final String result = await platform.invokeMethod('getMessage');
return result;
} on PlatformException catch (e) {
return "Failed to get message: '${e.message}'.";
}
}
}
- ArkTS端代码:
import { MethodChannel, MethodCallHandler } from '@ohos.flutter';
const channel = new MethodChannel('com.example.flutter/native');
channel.setMethodCallHandler((call) => {
if (call.method === 'getMessage') {
return Promise.resolve('Hello from ArkTS');
}
return Promise.resolve(null);
});
- 调用示例:
void fetchMessage() async {
String message = await NativeBridge().getNativeMessage();
print(message); // 输出: Hello from ArkTS
}
通过这种方式,Flutter与ArkTS可以实现双向通信,Flutter可以调用ArkTS中的方法,并获取返回结果。
在HarmonyOS鸿蒙Next中,Flutter与原生ArkTS的交互可以通过平台通道(Platform Channel)实现。以下是一个简单示例:
- Flutter端:定义MethodChannel并调用原生方法。
import 'package:flutter/services.dart';
class NativeBridge {
static const platform = MethodChannel('com.example/native');
Future<String> getNativeData() async {
try {
return await platform.invokeMethod('getData');
} on PlatformException catch (e) {
return "Failed to get data: ${e.message}";
}
}
}
- ArkTS端:注册MethodChannel并实现方法。
import { Ability, AbilityContext, MethodChannel } from '@ohos.ability.featureAbility';
export default class MainAbility extends Ability {
onCreate() {
const channel = new MethodChannel('com.example/native');
channel.setMethodCallHandler((method, args) => {
if (method === 'getData') {
return Promise.resolve('Hello from ArkTS');
}
return Promise.reject('Method not implemented');
});
}
}
通过这种方式,Flutter可以调用ArkTS中的方法并获取返回数据,实现跨平台交互。