【Flutter 混合开发】嵌入原生View-iOS

【Flutter 混合开发】嵌入原生View-iOS,第1张

概述Flutter 混合开发系列 包含如下: 嵌入原生View-Android 嵌入原生View-iOS 与原生通信-MethodChannel 与原生通信-BasicMessageChannel 与原生

@H_502_2@

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 Foundationimport Flutterclass 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 Foundationimport Flutterclass 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 UIKitimport 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的参数'},)
creationParams :传递的参数,插件可以将此参数传递给 AndroIDVIEw 的构造函数。creationParamsCodec :将 creationParams 编码后再发送给平台侧,它应该与传递给构造函数的编解码器匹配。值的范围:StandardMessageCodecJsONMessageCodecStringCodecBinaryCodec

修改 MyFlutterVIEw :

import Foundationimport Flutterclass MyFlutterVIEw: NSObject,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',);      } else if (defaultTargetPlatform == TargetPlatform.iOS) {        return UiKitVIEw(          vIEwType: 'plugins.Flutter.io/custom_platform_vIEw',);      }    }    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 Foundationimport Flutterclass MyFlutterVIEw: NSObject,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 Foundationimport Flutterclass MyFlutterVIEw: NSObject,result:FlutterResult) in            if (call.method == "setText") {                if let dict = call.arguments as? Dictionary<String,年龄:\(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','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',body: Column(children: [        Row(          children: [            Raisedbutton(              child: Text('传递参数给原生VIEw'),onpressed: () {                platform                    .invokeMethod('setText','age': 18});              },Raisedbutton(              child: Text('$_data'),onpressed: () async {                var result = await platform                    .invokeMethod('getData','age': 18});                setState(() {                  _data = '${result['name']},${result['age']}';                });              },],Expanded(child: Container(color: colors.red,child: platformVIEw())),Expanded(child: Container(color: colors.blue,Expanded(child: Container(color: colors.yellow,);  }}

此时点击 传递参数给原生VIEw 按钮哪个VIEw会改变内容,实际上只有最后一个会改变。

如何改变指定VIEw的内容?重点是 MethodChannel,只需修改上面3个通道的名称不相同即可:

第一种方法:将一个唯一 ID 通过初始化参数传递给原生 VIEw,原生 VIEw使用这个ID 构建不同名称的 MethodChannel。第二种方法(推荐):原生 VIEw 生成时,系统会为其生成唯一ID:vIEwID,使用 vIEwID 构建不同名称的 MethodChannel。

原生 VIEw 使用 vIEwID 构建不同名称的 MethodChannel:

import Foundationimport Flutterclass MyFlutterVIEw: NSObject,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)",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'));  },)

给第一个发送消息:

platforms[0]    .invokeMethod('setText','age': 18});

交流

老孟Flutter博客(330个控件用法+实战入门系列文章):http://laomengit.com

欢迎加入Flutter交流群(微信:laomengit)、关注公众号【老孟Flutter】:

总结

以上是内存溢出为你收集整理的【Flutter 混合开发】嵌入原生View-iOS全部内容,希望文章能够帮你解决【Flutter 混合开发】嵌入原生View-iOS所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1000445.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存