凉凉凉了 發表於 2020-10-18 21:38:00

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

<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201018213818619-1774223380.png"></p>
<blockquote>
<p>Flutter 混合开发系列 包含如下:</p>
<ul>
<li>嵌入原生View-Android</li>
<li><strong>嵌入原生View-iOS</strong></li>
<li>与原生通信-MethodChannel</li>
<li>与原生通信-BasicMessageChannel</li>
<li>与原生通信-EventChannel</li>
<li>添加 Flutter 到 Android Activity</li>
<li>添加 Flutter 到 Android Fragment</li>
<li>添加 Flutter 到 iOS</li>
</ul>
<p>每个工作日分享一篇,欢迎关注、点赞及转发。</p>
</blockquote>
<h3 id="ios-view">iOS View</h3>
<p>建议使用 Xcode 进行开发,在 Android Studio 左侧 project tab下选中 ios 目录下任意一个文件,右上角会出现 <strong>Open iOS module in Xcode</strong> ,</p>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201018213820536-83732165.png"></p>
<p>点击即可打开,打开后如下:</p>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201018213821847-1192660487.png"></p>
<p>在<strong>Runner</strong> 目录下创建 iOS View,此 View 继承 <strong>FlutterPlatformView</strong> ,返回一个简单的 <strong>UILabel</strong> :</p>
<pre><code class="language-dart">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() -&gt; UIView {
      return label
    }   
}
</code></pre>
<ul>
<li><strong>getView</strong> :返回iOS View</li>
</ul>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201018213823179-720270054.png"></p>
<h3 id="注册platformview">注册PlatformView</h3>
<p>创建 MyFlutterViewFactory:</p>
<pre><code class="language-dart">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?) -&gt; FlutterPlatformView {
      return MyFlutterView(frame,viewID: viewId,args: args,messenger: messenger)
    }
   
    func createArgsCodec() -&gt; FlutterMessageCodec &amp; NSObjectProtocol {
      return FlutterStandardMessageCodec.sharedInstance()
    }
}

</code></pre>
<p>在 <strong>AppDelegate</strong> 中注册:</p>
<pre><code class="language-dart">import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: ?
) -&gt; 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)
}
}

</code></pre>
<p>记住 <strong>plugins.flutter.io/custom_platform_view</strong> ,这个字符串在 Flutter 中需要与其保持一致。</p>
<h3 id="嵌入flutter">嵌入Flutter</h3>
<p>在 Flutter 中调用</p>
<pre><code class="language-dart">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(),
      ),
    );
}
}
</code></pre>
<p>上面嵌入的是 iOS View,因此通过 <strong>defaultTargetPlatform == TargetPlatform.iOS</strong> 判断当前平台加载,在 iOS 上运行效果:</p>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201018213823978-1597673461.png"></p>
<h3 id="设置初始化参数">设置初始化参数</h3>
<p>Flutter 端修改如下:</p>
<pre><code class="language-dart">UiKitView(
          viewType: 'plugins.flutter.io/custom_platform_view',
          creationParams: {'text': 'Flutter传给IOSTextView的参数'},
          creationParamsCodec: StandardMessageCodec(),
      )
</code></pre>
<ul>
<li><strong>creationParams</strong> :传递的参数,插件可以将此参数传递给 AndroidView 的构造函数。</li>
<li><strong>creationParamsCodec</strong> :将 creationParams 编码后再发送给平台侧,它应该与传递给构造函数的编解码器匹配。值的范围:
<ul>
<li>StandardMessageCodec</li>
<li>JSONMessageCodec</li>
<li>StringCodec</li>
<li>BinaryCodec</li>
</ul>
</li>
</ul>
<p>修改 MyFlutterView :</p>
<pre><code class="language-dart">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() -&gt; UIView {
      return label
    }
   
}

</code></pre>
<p>最终效果:</p>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201018213824661-668681268.png"></p>
<h3 id="flutter-向-ios-view-发送消息">Flutter 向 iOS View 发送消息</h3>
<p>修改 Flutter 端,创建 <strong>MethodChannel</strong> 用于通信:</p>
<pre><code class="language-dart">class PlatformViewDemo extends StatefulWidget {
@override
_PlatformViewDemoState createState() =&gt; _PlatformViewDemoState();
}

class _PlatformViewDemoState extends State&lt;PlatformViewDemo&gt; {
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()),
      ]),
    );
}
}
</code></pre>
<p>在 原生View 中也创建一个 <strong>MethodChannel</strong> 用于通信:</p>
<pre><code class="language-dart">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&lt;String, Any&gt; {
                  let name:String = dict["name"] as? String ?? ""
                  let age:Int = dict["age"] as? Int ?? -1
                  self.label.text = "hello,\(name),年龄:\(age)"
                }
            }
      }
    }
   
    func view() -&gt; UIView {
      return label
    }
   
}

</code></pre>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201018213825931-1673746606.gif"></p>
<h3 id="flutter-向-android-view-获取消息">Flutter 向 Android View 获取消息</h3>
<p>与上面发送信息不同的是,Flutter 向原生请求数据,原生返回数据到 Flutter 端,修改 <strong>MyFlutterView onMethodCall</strong>:</p>
<pre><code class="language-dart">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&lt;String, Any&gt; {
                  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&lt;String, Any&gt; {
                  let name:String = dict["name"] as? String ?? ""
                  let age:Int = dict["age"] as? Int ?? -1
                  result(["name":name,"age":age])
                }
            }
      }
    }
   
    func view() -&gt; UIView {
      return label
    }
   
}

</code></pre>
<p><strong>result()</strong> 是返回的数据。</p>
<p>Flutter 端接收数据:</p>
<pre><code class="language-dart">var _data = '获取数据';

RaisedButton(
child: Text('$_data'),
onPressed: () async {
    var result = await platform
      .invokeMethod('getData', {'name': 'laomeng', 'age': 18});
    setState(() {
      _data = '${result['name']},${result['age']}';
    });
},
),
</code></pre>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201018213826253-1999581158.gif"></p>
<h3 id="解决多个原生view通信冲突问题">解决多个原生View通信冲突问题</h3>
<p>当然页面有3个原生View,</p>
<pre><code class="language-dart">class PlatformViewDemo extends StatefulWidget {
@override
_PlatformViewDemoState createState() =&gt; _PlatformViewDemoState();
}

class _PlatformViewDemoState extends State&lt;PlatformViewDemo&gt; {
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())),
      ]),
    );
}
}
</code></pre>
<p>此时点击 <strong>传递参数给原生View</strong> 按钮哪个View会改变内容,实际上只有最后一个会改变。</p>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201018213826815-1508060639.gif"></p>
<p>如何改变指定View的内容?重点是 <strong>MethodChannel</strong>,只需修改上面3个通道的名称不相同即可:</p>
<ul>
<li><strong>第一种方法</strong>:将一个唯一 id 通过初始化参数传递给原生 View,原生 View使用这个id 构建不同名称的 <strong>MethodChannel</strong>。</li>
<li><strong>第二种方法(推荐)</strong>:原生 View 生成时,系统会为其生成唯一id:viewId,使用 viewId 构建不同名称的 <strong>MethodChannel</strong>。</li>
</ul>
<p>原生 View 使用 viewId 构建不同名称的 <strong>MethodChannel</strong>:</p>
<pre><code class="language-dart">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() -&gt; UIView {
      return label
    }
   
}

</code></pre>
<p>Flutter 端为每一个原生 View 创建不同的<strong>MethodChannel</strong>:</p>
<pre><code class="language-dart">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(),
)
</code></pre>
<p>给第一个发送消息:</p>
<pre><code class="language-dart">platforms
    .invokeMethod('setText', {'name': 'laomeng', 'age': 18});
</code></pre>
<p><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201018213827818-270762580.gif"></p>
<h2 id="交流">交流</h2>
<p>老孟Flutter博客(330个控件用法+实战入门系列文章):http://laomengit.com</p>
<p>欢迎加入Flutter交流群(微信:laomengit)、关注公众号【老孟Flutter】:</p>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201018213828493-735594902.png"></td>
<td><img src="https://img2020.cnblogs.com/other/467322/202010/467322-20201018213828901-1783786605.png"></td>
</tr>
</tbody>
</table><br><br>
来源:https://www.cnblogs.com/mengqd/p/13837301.html
頁: [1]
查看完整版本: 【Flutter 混合开发】嵌入原生View-iOS