【Flutter 混合开发】嵌入原生View-iOS
Flutter 混合开发系列 包含如下:
- 嵌入原生View-Android
- 嵌入原生View-iOS
- 与原生通信-MethodChannel
- 与原生通信-BasicMessageChannel
- 与原生通信-EventChannel
- 添加 Flutter 到 Android Activity
- 添加 Flutter 到 Android Fragment
- 添加 Flutter 到 iOS
每个工作日分享一篇,欢迎关注、点赞及转发。
iOS View
建议使用 Xcode 进行开发,在 Android Studio 左侧 project tab下选中 ios 目录下任意一个文件,右上角会出现 Open iOS module in Xcode ,
点击即可打开,打开后如下:
在Runner 目录下创建 iOS View,此 View 继承 FlutterPlatformView ,返回一个简单的 UILabel :
import Foundation
import Flutter
class MyFlutterView: NSObject,FlutterPlatformView {
let label = UILabel()
init(_ frame: CGRect,viewID: Int64,args :Any?,messenger :FlutterBinaryMessenger) {
label.text = "我是 iOS View"
}
func view() -> UIView {
return label
}
}
- getView :返回iOS View
注册PlatformView
创建 MyFlutterViewFactory:
import Foundation
import Flutter
class MyFlutterViewFactory: NSObject,FlutterPlatformViewFactory {
var messenger:FlutterBinaryMessenger
init(messenger:FlutterBinaryMessenger) {
self.messenger = messenger
super.init()
}
func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?) -> FlutterPlatformView {
return MyFlutterView(frame,viewID: viewId,args: args,messenger: messenger)
}
func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol {
return FlutterStandardMessageCodec.sharedInstance()
}
}
在 AppDelegate 中注册:
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
let registrar:FlutterPluginRegistrar = self.registrar(forPlugin: "plugins.flutter.io/custom_platform_view_plugin")!
let factory = MyFlutterViewFactory(messenger: registrar.messenger())
registrar.register(factory, withId: "plugins.flutter.io/custom_platform_view")
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
记住 plugins.flutter.io/custom_platform_view ,这个字符串在 Flutter 中需要与其保持一致。
嵌入Flutter
在 Flutter 中调用
class PlatformViewDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
Widget platformView() {
if (defaultTargetPlatform == TargetPlatform.android) {
return AndroidView(
viewType: 'plugins.flutter.io/custom_platform_view',
onPlatformViewCreated: (viewId) {
print('viewId:$viewId');
platforms
.add(MethodChannel('com.flutter.guide.MyFlutterView_$viewId'));
},
creationParams: {'text': 'Flutter传给AndroidTextView的参数'},
creationParamsCodec: StandardMessageCodec(),
);
}else if(defaultTargetPlatform == TargetPlatform.iOS){
return UiKitView(
viewType: 'plugins.flutter.io/custom_platform_view',
);
}
}
return Scaffold(
appBar: AppBar(),
body: Center(
child: platformView(),
),
);
}
}
上面嵌入的是 iOS View,因此通过 defaultTargetPlatform == TargetPlatform.iOS 判断当前平台加载,在 iOS 上运行效果:
设置初始化参数
Flutter 端修改如下:
UiKitView(
viewType: 'plugins.flutter.io/custom_platform_view',
creationParams: {'text': 'Flutter传给IOSTextView的参数'},
creationParamsCodec: StandardMessageCodec(),
)
- creationParams :传递的参数,插件可以将此参数传递给 AndroidView 的构造函数。
- creationParamsCodec :将 creationParams 编码后再发送给平台侧,它应该与传递给构造函数的编解码器匹配。值的范围:
- StandardMessageCodec
- JSONMessageCodec
- StringCodec
- BinaryCodec
修改 MyFlutterView :
import Foundation
import Flutter
class MyFlutterView: NSObject,FlutterPlatformView {
let label = UILabel()
init(_ frame: CGRect,viewID: Int64,args :Any?,messenger :FlutterBinaryMessenger) {
super.init()
if(args is NSDictionary){
let dict = args as! NSDictionary
label.text = dict.value(forKey: "text") as! String
}
}
func view() -> UIView {
return label
}
}
最终效果:
Flutter 向 iOS View 发送消息
修改 Flutter 端,创建 MethodChannel 用于通信:
class PlatformViewDemo extends StatefulWidget {
@override
_PlatformViewDemoState createState() => _PlatformViewDemoState();
}
class _PlatformViewDemoState extends State<PlatformViewDemo> {
static const platform =
const MethodChannel('com.flutter.guide.MyFlutterView');
@override
Widget build(BuildContext context) {
Widget platformView() {
if (defaultTargetPlatform == TargetPlatform.android) {
return AndroidView(
viewType: 'plugins.flutter.io/custom_platform_view',
creationParams: {'text': 'Flutter传给AndroidTextView的参数'},
creationParamsCodec: StandardMessageCodec(),
);
} else if (defaultTargetPlatform == TargetPlatform.iOS) {
return UiKitView(
viewType: 'plugins.flutter.io/custom_platform_view',
creationParams: {'text': 'Flutter传给IOSTextView的参数'},
creationParamsCodec: StandardMessageCodec(),
);
}
}
return Scaffold(
appBar: AppBar(),
body: Column(children: [
RaisedButton(
child: Text('传递参数给原生View'),
onPressed: () {
platform.invokeMethod('setText', {'name': 'laomeng', 'age': 18});
},
),
Expanded(child: platformView()),
]),
);
}
}
在 原生View 中也创建一个 MethodChannel 用于通信:
import Foundation
import Flutter
class MyFlutterView: NSObject,FlutterPlatformView {
let label = UILabel()
init(_ frame: CGRect,viewID: Int64,args :Any?,messenger :FlutterBinaryMessenger) {
super.init()
if(args is NSDictionary){
let dict = args as! NSDictionary
label.text = dict.value(forKey: "text") as! String
}
let methodChannel = FlutterMethodChannel(name: "com.flutter.guide.MyFlutterView", binaryMessenger: messenger)
methodChannel.setMethodCallHandler { (call, result) in
if (call.method == "setText") {
if let dict = call.arguments as? Dictionary<String, Any> {
let name:String = dict["name"] as? String ?? ""
let age:Int = dict["age"] as? Int ?? -1
self.label.text = "hello,\(name),年龄:\(age)"
}
}
}
}
func view() -> UIView {
return label
}
}
Flutter 向 Android View 获取消息
与上面发送信息不同的是,Flutter 向原生请求数据,原生返回数据到 Flutter 端,修改 MyFlutterView onMethodCall:
import Foundation
import Flutter
class MyFlutterView: NSObject,FlutterPlatformView {
let label = UILabel()
init(_ frame: CGRect,viewID: Int64,args :Any?,messenger :FlutterBinaryMessenger) {
super.init()
if(args is NSDictionary){
let dict = args as! NSDictionary
label.text = dict.value(forKey: "text") as! String
}
let methodChannel = FlutterMethodChannel(name: "com.flutter.guide.MyFlutterView", binaryMessenger: messenger)
methodChannel.setMethodCallHandler { (call, result:FlutterResult) in
if (call.method == "setText") {
if let dict = call.arguments as? Dictionary<String, Any> {
let name:String = dict["name"] as? String ?? ""
let age:Int = dict["age"] as? Int ?? -1
self.label.text = "hello,\(name),年龄:\(age)"
}
}else if (call.method == "getData") {
if let dict = call.arguments as? Dictionary<String, Any> {
let name:String = dict["name"] as? String ?? ""
let age:Int = dict["age"] as? Int ?? -1
result(["name":name,"age":age])
}
}
}
}
func view() -> UIView {
return label
}
}
result() 是返回的数据。
Flutter 端接收数据:
var _data = '获取数据';
RaisedButton(
child: Text('$_data'),
onPressed: () async {
var result = await platform
.invokeMethod('getData', {'name': 'laomeng', 'age': 18});
setState(() {
_data = '${result['name']},${result['age']}';
});
},
),
解决多个原生View通信冲突问题
当然页面有3个原生View,
class PlatformViewDemo extends StatefulWidget {
@override
_PlatformViewDemoState createState() => _PlatformViewDemoState();
}
class _PlatformViewDemoState extends State<PlatformViewDemo> {
static const platform =
const MethodChannel('com.flutter.guide.MyFlutterView');
var _data = '获取数据';
@override
Widget build(BuildContext context) {
Widget platformView() {
if (defaultTargetPlatform == TargetPlatform.android) {
return AndroidView(
viewType: 'plugins.flutter.io/custom_platform_view',
creationParams: {'text': 'Flutter传给AndroidTextView的参数'},
creationParamsCodec: StandardMessageCodec(),
);
} else if (defaultTargetPlatform == TargetPlatform.iOS) {
return UiKitView(
viewType: 'plugins.flutter.io/custom_platform_view',
creationParams: {'text': 'Flutter传给IOSTextView的参数'},
creationParamsCodec: StandardMessageCodec(),
);
}
}
return Scaffold(
appBar: AppBar(),
body: Column(children: [
Row(
children: [
RaisedButton(
child: Text('传递参数给原生View'),
onPressed: () {
platform
.invokeMethod('setText', {'name': 'laomeng', 'age': 18});
},
),
RaisedButton(
child: Text('$_data'),
onPressed: () async {
var result = await platform
.invokeMethod('getData', {'name': 'laomeng', 'age': 18});
setState(() {
_data = '${result['name']},${result['age']}';
});
},
),
],
),
Expanded(child: Container(color: Colors.red, child: platformView())),
Expanded(child: Container(color: Colors.blue, child: platformView())),
Expanded(child: Container(color: Colors.yellow, child: platformView())),
]),
);
}
}
此时点击 传递参数给原生View 按钮哪个View会改变内容,实际上只有最后一个会改变。
如何改变指定View的内容?重点是 MethodChannel,只需修改上面3个通道的名称不相同即可:
- 第一种方法:将一个唯一 id 通过初始化参数传递给原生 View,原生 View使用这个id 构建不同名称的 MethodChannel。
- 第二种方法(推荐):原生 View 生成时,系统会为其生成唯一id:viewId,使用 viewId 构建不同名称的 MethodChannel。
原生 View 使用 viewId 构建不同名称的 MethodChannel:
import Foundation
import Flutter
class MyFlutterView: NSObject,FlutterPlatformView {
let label = UILabel()
init(_ frame: CGRect,viewID: Int64,args :Any?,messenger :FlutterBinaryMessenger) {
super.init()
if(args is NSDictionary){
let dict = args as! NSDictionary
label.text = dict.value(forKey: "text") as! String
}
let methodChannel = FlutterMethodChannel(name: "com.flutter.guide.MyFlutterView_\(viewID)", binaryMessenger: messenger)
methodChannel.setMethodCallHandler { (call, result:FlutterResult) in
...
}
}
func view() -> UIView {
return label
}
}
Flutter 端为每一个原生 View 创建不同的MethodChannel:
var platforms = [];
UiKitView(
viewType: 'plugins.flutter.io/custom_platform_view',
onPlatformViewCreated: (viewId) {
print('viewId:$viewId');
platforms
.add(MethodChannel('com.flutter.guide.MyFlutterView_$viewId'));
},
creationParams: {'text': 'Flutter传给AndroidTextView的参数'},
creationParamsCodec: StandardMessageCodec(),
)
给第一个发送消息:
platforms[0]
.invokeMethod('setText', {'name': 'laomeng', 'age': 18});
交流
老孟Flutter博客(330个控件用法+实战入门系列文章):http://laomengit.com
欢迎加入Flutter交流群(微信:laomengit)、关注公众号【老孟Flutter】:
【Flutter 混合开发】嵌入原生View-iOS的更多相关文章
- 【Flutter 混合开发】嵌入原生View-Android
Flutter 混合开发系列 包含如下: 嵌入原生View-Android 嵌入原生View-IOS 与原生通信-MethodChannel 与原生通信-BasicMessageChannel 与原生 ...
- 【Flutter 混合开发】添加 Flutter 到 iOS
Flutter 混合开发系列 包含如下: 嵌入原生View-Android 嵌入原生View-iOS 与原生通信-MethodChannel 与原生通信-BasicMessageChannel 与原生 ...
- 【Flutter 混合开发】与原生通信-MethodChannel
Flutter 混合开发系列 包含如下: 嵌入原生View-Android 嵌入原生View-iOS 与原生通信-MethodChannel 与原生通信-BasicMessageChannel 与原生 ...
- 【Flutter 混合开发】与原生通信-BasicMessageChannel
Flutter 混合开发系列 包含如下: 嵌入原生View-Android 嵌入原生View-iOS 与原生通信-MethodChannel 与原生通信-BasicMessageChannel 与原生 ...
- 【Flutter 混合开发】与原生通信-EventChannel
Flutter 混合开发系列 包含如下: 嵌入原生View-Android 嵌入原生View-iOS 与原生通信-MethodChannel 与原生通信-BasicMessageChannel 与原生 ...
- 【Flutter 混合开发】添加 Flutter 到 Android Fragment
Flutter 混合开发系列 包含如下: 嵌入原生View-Android 嵌入原生View-iOS 与原生通信-MethodChannel 与原生通信-BasicMessageChannel 与原生 ...
- 【Flutter 混合开发】添加 Flutter 到 Android Activity
Flutter 混合开发系列 包含如下: 嵌入原生View-Android 嵌入原生View-iOS 与原生通信-MethodChannel 与原生通信-BasicMessageChannel 与原生 ...
- APP手机商城系统选择,混合开发与原生开发哪个好?
关于手机APP开发用混合还是原生现在说法不一,有说混合开发好:时间短.费用低.效果也不错,有说原生开发好,原生APP在性能方面比较好.而商城系统中的手机APP用混合开发还是原生开发比较好呢? 最近我参 ...
- Flutter混合开发:Android接入Flutter
Flutter Google推出已经已经一年多了,单个 Flutter 项目的开发流程已经很成熟了.对与个人开发者来说使用 Flutter 开发一个跨平台的App挺有意思.但是对于现有的项目改造来说还 ...
随机推荐
- ui自动化---select标签和浏览器等待
一.select 引入模块from selenium.webdriver.support.select import Select Select(select).select_by_value('') ...
- python之Lambda
Python 匿名函数lambda lambda表达式在“:”后只能有一个表达式.也就是说,在def中,用return可以返回的也可以放在lambda后面,不能用return返回的也不能定义在py ...
- python 3 for与while嵌套
- [LeetCode]1084. 销售分析III(Mysql,having+聚合函数)
题目 Table: Product +--------------+---------+ | Column Name | Type | +--------------+---------+ | pro ...
- node 进阶 | 通过node中如何捕获异常阐述express的特点
node如何捕获异常 node基于js的单线程,有了非阻塞异步回调的概念,但是在处理多个并发连接时,并发环境要求高,最重要的是单线程,单核CPU,一个进程crash则web服务都crash,但是为什么 ...
- hystrix源码之插件
HystrixPlugins 获取并发相关类(HystrixConcurrencyStrategy).事件通知类(HystrixEventNotifier).度量信息类(HystrixMetricsP ...
- 再见了SpringMVC!这个框架有点厉害,甚至干掉了Servlet!
# 前言 对 Java 开发者来说, Spring 发布 5.0 正式版,而新版 Spring 的一大特色,就是 Reactive Web 方案 Web Flux,这是用来替代 Spring Web ...
- 可以定时的FTP FTP如何实现每天定时上传文件
FTP上传一般都是一次性上传,我们在工作中总有一些文件,需要每天上传一次.有这么一款ftp上传工具是具有定时功能的.每天自动定时上传省时省力还操作简单. 工具名称:服务器管理工具(下载地址:http: ...
- 面试官:一个 TCP 连接可以发多少个 HTTP 请求?
曾经有这么一道面试题:从 URL 在浏览器被被输入到页面展现的过程中发生了什么? 相信大多数准备过的同学都能回答出来,但是如果继续问:收到的 HTML 如果包含几十个图片标签,这些图片是以什么方式 ...
- Java知识系统回顾整理01基础05控制流程03 while
while和do-while循环语句 一.while:条件为true时 重复执行 只要while中的表达式成立,就会不断地循环执行 public class HelloWorld { public s ...