HarmonyOS Flutter平台调用Demo

📅 发布时间:2026/7/12 21:54:27 👁️ 浏览次数:
HarmonyOS Flutter平台调用Demo
欢迎大家加入开源鸿蒙跨平台社区openharmonyFlutter 平台调用 Demo本文介绍在 Flutter鸿蒙跨平台项目中通过MethodChannel实现 Flutter 与鸿蒙原生双向通信的完整流程涵盖 Flutter 侧调用、鸿蒙侧处理、EventChannel 数据流、双向通信三个维度。一、整体架构Flutter (Dart) 鸿蒙原生 (ArkTS) ───────────────── ────────────────────── MethodChannel.invokeMethod() ←→ MethodCallHandler.onMethodCall() EventChannel.receiveBroadcastStream() ← 原生持续推送 channel.setMethodCallHandler() ← 原生主动回调 Flutter两端共享同一个 Channel 名称字符串标识通过BinaryMessenger进行二进制消息传递。二、Flutter 侧MethodChannel 调用定义 Channel 常量const_kMethodChannelcom.example.test1/platform_demo;const_kEventChannelcom.example.test1/platform_demo_event;调用原生方法staticconst_channelMethodChannel(_kMethodChannel);Futurevoid_call(Stringmethod,[MapString,dynamic?args])async{try{finalresultawait_channel.invokeMethod(method,args);_log(method,result?.toString()??null);}onPlatformExceptioncatch(e){_log(method,${e.code}:${e.message},isError:true);}onMissingPluginException{// 原生侧未实现时降级为模拟数据_log(method,_mockResult(method,args));}}MissingPluginException降级策略保证在未接入原生实现时 Demo 仍可正常运行。三、Flutter 侧监听原生主动回调原生可以主动调用 Flutter 侧的setMethodCallHandler_channel.setMethodCallHandler((call)async{if(call.methodpushMessageToFlutter){finalmsgcall.arguments?[message]asString???;setState((){_messages.add(_ChatMsg(text:原生 → Flutter:$msg,isNative:true));});}returnnull;});四、Flutter 侧EventChannel 数据流EventChannel适用于原生持续推送数据如传感器、位置更新consteventChannelEventChannel(_kEventChannel);_subeventChannel.receiveBroadcastStream().listen((event)setState(()_events.insert(0,event.toString())),onError:(e)_startMockStream(),// 降级为模拟流);五、鸿蒙侧注册 MethodChannel在EntryAbility.configureFlutterEngine中注册 Channel 并设置处理器letmessenger:BinaryMessengerflutterEngine.dartExecutor.getBinaryMessenger();this.demoChannelnewMethodChannel(messenger,DEMO_CHANNEL_NAME);letdemoHandler:MethodCallHandler{onMethodCall:(call:MethodCall,result:MethodResult){switch(call.method){casegetDeviceInfo:this.handleGetDeviceInfo(result);break;casegetBatteryLevel:this.handleGetBattery(result);break;caseecho:letmsgcall.argument(message)asstring;result.success(原生回响: msg);break;default:result.notImplemented();}}};this.demoChannel.setMethodCallHandler(demoHandler);六、鸿蒙侧系统 API 调用获取设备信息ArkTS 要求对象字面量必须对应显式声明的接口arkts-no-untyped-obj-literalsinterfaceDeviceInfo{brand:string;model:string;osVersion:string;platform:string;}privatehandleGetDeviceInfo(result:MethodResult):void{letinfo:DeviceInfo{// 必须使用显式接口类型brand:deviceInfo.brand,model:deviceInfo.productModel,osVersion:deviceInfo.osFullName,platform:ohos};result.success(JSON.stringify(info));}获取电池电量import{batteryInfo}fromkit.BasicServicesKit;result.success(batteryInfo.batterySOC);// 返回 0~100 整数获取网络状态connection不属于kit.BasicServicesKit需单独导入importconnectionfromohos.net.connection;// ✅ 正确导入方式constnetHandleconnection.getDefaultNetSync();constisConnected:booleannetHandle.netId0;result.success(isConnected?已连接:未连接);七、常见编译错误与修复错误原因修复arkts-no-untyped-obj-literals对象字面量无显式类型声明interface并使用let x: MyInterface {...}connection is not exported from Kitconnection模块路径错误改为import connection from ohos.net.connectionarkts-no-any-unknown变量类型推断为any为所有变量标注明确类型MissingPluginExceptionFlutter 侧 Channel 名称不匹配确保 Flutter 和鸿蒙两端 Channel 名称完全一致总结通信模式适用场景核心 APIFlutter → 原生单次获取设备信息、触发震动MethodChannel.invokeMethod原生 → Flutter单次原生主动推送结果channel.setMethodCallHandler原生 → Flutter持续传感器数据、位置更新EventChannel.receiveBroadcastStream双向通信即时消息、指令响应MethodChannel双端互调