iOS Flutter MethodChannel 双向通信
原创 2023-02-12
MethodChannel 是 Flutter提供的最常用的和 Native App 双向通信的方式。本文将演示这种通信方式的使用。
参考文档 Architectural overview: platform channels。以 Flutter 默认创建的脚手架工程为例说明。
Flutter 端的调用
首先,构建MethodChannel
,可以理解为数据信道,信道通过名称唯一定位,通信时需确保 Flutter 端和 Native 端的MethodChannel
name 是一致的,信道名称采用反域名的形式,比如:com.easeapi.flutter
。
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
修改脚手架工程main.dart
文件的_MyHomePageState
类:
static const channel = MethodChannel('com.easeapi.MethodChannel');
@override
void initState() {
// TODO: implement initState
super.initState();
//监听来自native的事件,并向native返回结果。
channel.setMethodCallHandler((call) {
print(call.method);
print(call.arguments);
return Future.value("hello native");
});
}
void _incrementCounter() async {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
//请求native方法,并获取结果
String result = await channel.invokeMethod('send_to_ios', {"name": "easeapi"});
print('get native result' + $result');
}
iOS Native 端的调用
AppDelegate
类中:
let channel = FlutterMethodChannel(name: "com.easeapi.MethodChannel", binaryMessenger: controller.binaryMessenger)
//监听来自flutter的调用
channel.setMethodCallHandler { (call: FlutterMethodCall, result:@escaping FlutterResult) in
if (call.method == "send_to_ios") {
result("hello flutter");
}
//从iOS层调用flutter方法
channel.invokeMethod("send_to_flutter", arguments: ["key": "value"], result: { (_result) in
print(_result as? String)
})
}
其中,FlutterMethodChannel
的 binaryMessenger
参数需要传入FlutterViewController
的binaryMessenger
。
完成修改,运行ios/Runner.xcworkspac
。点击按钮可以看到终端中打印通信日志。
关于 FlutterViewController
FlutterViewController
在 Flutter 中是个很重要的存在,它是Flutter的容器,或者说是Flutter的画板。实际上FlutterViewController
就是一个UIViewController
,和原生App不同的是,Flutter中的所有内容都在于这个ViewController内做渲染,包括Flutter
内的页面导航跳转。
相关文章:
iOS Flutter 开发环境部署
iOS Asset Catalog and Bundle
iOS Sign With Apple实践
iOS系统如何获取用户的本机手机号
iOS安全:Tweak开发环境及入门
发表留言
您的电子邮箱地址不会被公开,必填项已用*标注。
留言板