💡
原文中文,约2000字,阅读约需5分钟。
📝
内容提要
Flutter的MethodChannel可以实现Flutter和Native App之间的双向通信,本文以Flutter默认创建的脚手架工程为例,介绍了MethodChannel的使用,Flutter端和Native端都需要构建MethodChannel,并且保证MethodChannel的name一致,FlutterViewController的binaryMessenger也需要传入。运行后可以看到通信日志。Flutter和Native App之间的双向通信可以通过MethodChannel实现。
🎯
关键要点
- MethodChannel 是 Flutter 提供的与 Native App 双向通信的主要方式。
- 本文以 Flutter 默认创建的脚手架工程为例,演示 MethodChannel 的使用。
- Flutter 端和 Native 端都需要构建 MethodChannel,并确保名称一致,采用反域名形式。
- 在 Flutter 端,使用 setMethodCallHandler 监听来自 Native 的事件,并返回结果。
- 在 Native 端,使用 FlutterMethodChannel 监听来自 Flutter 的调用,并可以从 iOS 层调用 Flutter 方法。
- FlutterMethodChannel 的 binaryMessenger 参数需要传入 FlutterViewController 的 binaryMessenger。
- 运行后可以在终端中查看到通信日志,验证双向通信的成功。
➡️