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

移动开发 作者: 2024-08-25 08:05:02
Flutter 混合开发系列 包含如下: 嵌入原生View-Android 嵌入原生View-iOS 与原生通信-MethodChannel 与原生通信-BasicMessageChannel 与原生

iOS View

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

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()
    }
}

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)
  }
}

嵌入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(),),);
  }
}

设置初始化参数

UiKitView(
          viewType: 'plugins.flutter.io/custom_platform_view',creationParams: {'text': 'Flutter传给IOSTextView的参数'},)
  • creationParams :传递的参数,插件可以将此参数传递给 AndroidView 的构造函数。
  • creationParamsCodec :将 creationParams 编码后再发送给平台侧,它应该与传递给构造函数的编解码器匹配。值的范围:
    • StandardMessageCodec
    • JSONMessageCodec
    • StringCodec
    • BinaryCodec
import Foundation
import Flutter

class 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 发送消息

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()),]),);
  }
}
import Foundation
import Flutter

class 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 获取消息

import Foundation
import Flutter

class 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
    }
    
}

var _data = '获取数据';

RaisedButton(
  child: Text('$_data'),onPressed: () async {
    var result = await platform
        .invokeMethod('getData','age': 18});
    setState(() {
      _data = '${result['name']},${result['age']}';
    });
  },

解决多个原生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,);
  }
}
  • 第一种方法:将一个唯一 id 通过初始化参数传递给原生 View,原生 View使用这个id 构建不同名称的 MethodChannel
  • 第二种方法(推荐):原生 View 生成时,系统会为其生成唯一id:viewId,使用 viewId 构建不同名称的 MethodChannel
import Foundation
import Flutter

class 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
    }
    
}

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});
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_68287.html