Flutter学习之旅-混合开发Part2

什么是Platform View

为了能让一些现有的Native控件直接引用到Flutter App中,Flutter团队提供了Platform View,允许Native View嵌入到Flutter Widget体系中,完成Dart代码对Native View的控制。

Platform View主要包括:AndroidViewUIKitView

如何使用Platform View

AndroidView

class AndroidView extends StatefulWidget {
  
  const AndroidView({
    Key key,
    @required this.viewType,
    this.onPlatformViewCreated,
    this.hitTestBehavior = PlatformViewHitTestBehavior.opaque,
    this.layoutDirection,
    this.gestureRecognizers,
    this.creationParams,
    this.creationParamsCodec,
  }) : assert(viewType != null),
       assert(hitTestBehavior != null),
       assert(creationParams == null || creationParamsCodec != null),
       super(key: key);

  /// 嵌入Android视图的唯一标识符
  final String viewType;
  /// Platform View创建完成的回调
  final PlatformViewCreatedCallback onPlatformViewCreated;
  /// hit测试期间的行为
  final PlatformViewHitTestBehavior hitTestBehavior;
  /// 视图的文本方向
  final TextDirection layoutDirection;
  /// 用于处理时间冲突,对时间进行分发管理相关操作
  final Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers;
  /// 传给Android视图的参数,在Android视图构造的时候使用
  final dynamic creationParams;
  /// 对creationParams参数传递时进行的编码规则,如果creationParams不为null,该值必须不为null
  final MessageCodec<dynamic> creationParamsCodec;

  @override
  State<AndroidView> createState() => _AndroidViewState();
}

需要注意的是:

  • AndroidView仅支持Android API 20以上
  • 在Flutter中使用AndroidView对性能的开销比较大,应该尽量的避免使用

用Android Studio打开创建好的Flutter项目,在Android Studio顶部菜单Tools->Flutter->Open for Editing in Android Studio,


image

点击即可打开一个Android项目,包含引入的三方库:


image

在主项目中,创建用于嵌入Flutter中的Android View,此View继成自PlatformView:

class CustomFlutterView(private val context: Context, messenger: BinaryMessenger, private val viewId: Int, params: Map<String, Any>?): PlatformView,  MethodChannel.MethodCallHandler{


    private var binding: CustomFlutterViewBinding = CustomFlutterViewBinding.inflate(LayoutInflater.from(context))
    private var methodChannel: MethodChannel

    init {
        params?.also { binding.tvReceiverFlutterMsg.text = it["init"] as String }
        methodChannel = MethodChannel(messenger, "com.mufeng.flutter_native_view")
        methodChannel.setMethodCallHandler(this)
    }

    override fun getView(): View {
        binding.sendMsgToFlutter.setOnClickListener {
            methodChannel.invokeMethod("sendMsgToFlutter", mapOf("text" to "Hello, CustomFlutterView_$viewId"))
        }
        return binding.root
    }

    override fun dispose() {
        methodChannel.setMethodCallHandler(null)
        Log.e("TAG", "释放资源")
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        if (call.method == "updateText") {
            val author = call.argument("author") as String?

            binding.tvReceiverFlutterMsg.text = "Hello, $author"
        } else {
            result.notImplemented()
        }
    }
}
  • getView(): 返回要嵌入Flutter层次结构的Android View
  • dispose: 释放此VIew时调用,此方法调用后View不可用,此方法需要清除所有对象引用,否则会造成内存泄漏
  • messenger:用于消息传递,Flutter与原生通信时会用到此参数
  • viewId: View生成时会分配一个唯一ID
  • args:Flutter传递的初始化参数
注册PlatformView

创建一个PlatformViewFactory:

class CustomFlutterViewFactory(private val messenger: BinaryMessenger):  PlatformViewFactory(StandardMessageCodec.INSTANCE){
    override fun create(context: Context, viewId: Int, args: Any?): PlatformView {
        return CustomFlutterView(context, messenger, viewId, args as Map<String, Any>)
    }
}

创建CustomPlugin

class CustomPlugin : FlutterPlugin {

    companion object {

        const val VIEW_TYPE_ID: String = "com.mufeng.flutter_native_view/custom_platform_view"

        fun registerWith(registrar: PluginRegistry.Registrar) {
            registrar.platformViewRegistry()
                    .registerViewFactory(VIEW_TYPE_ID, CustomFlutterViewFactory(registrar.messenger()))
        }
    }

    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        val messenger: BinaryMessenger = binding.binaryMessenger
        binding.platformViewRegistry.registerViewFactory(VIEW_TYPE_ID, CustomFlutterViewFactory(messenger))
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {

    }
}

注意:VIEW_TYPE_ID 这个字符串需要和Flutter端保持一致

在App中MainActivity中注册:

class MainActivity: FlutterActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        flutterEngine.plugins.add(CustomPlugin())
    }
}

需要注意的是,如果我们是在开发Flutter Plugin时,是没有MainActivity的,则需要在对应的Plugin类下的onAttachedToEngine() 方法和registerWith()方法下修改

在Flutter中调用

class _MyHomePageState extends State<MyHomePage> {


  static const platform =
  const MethodChannel('com.mufeng.flutter_native_view');

  String result;

  @override
  void initState() {
    super.initState();
    platform.setMethodCallHandler((call) {
      setState(() {
        result = call.arguments['text'];
      });
      print("接收到Native传递的数据: ${call.arguments['text']}");
      return;
    });
  }


  @override
  Widget build(BuildContext context) {
    Widget platformView() {
      if (defaultTargetPlatform == TargetPlatform.android) {
        return AndroidView(
          viewType: "com.mufeng.flutter_native_view/custom_platform_view",
          creationParams: {'init': '来自Flutter传递的初始化参数'},
          creationParamsCodec: StandardMessageCodec(),
          onPlatformViewCreated: (viewId) {
            print('View 创建完成; ViewId: $viewId');
          },
        );
      }
    }
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Platform View',
          style: TextStyle(
              color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
        ),
        centerTitle: true,
      ),
      body: Column(
        children: [
          TextButton(onPressed: () {
            platform.invokeMethod('updateText', {'author': 'MuFeng'});
          }, child: Text('传递参数给原生View')),
          Text(result??'等待Native发送的数据'),
          Expanded(child: platformView()),
        ],
      ),
    );
  }
}

查看在Android中的运行效果:


image

image

image

UIKitView

class UiKitView extends StatefulWidget {
  
  const UiKitView({
    Key key,
    @required this.viewType,
    this.onPlatformViewCreated,
    this.hitTestBehavior = PlatformViewHitTestBehavior.opaque,
    this.layoutDirection,
    this.creationParams,
    this.creationParamsCodec,
    this.gestureRecognizers,
  }) : assert(viewType != null),
       assert(hitTestBehavior != null),
       assert(creationParams == null || creationParamsCodec != null),
       super(key: key);
  /// 嵌入iOS视图的唯一标识符
  final String viewType;
  /// Platform View创建完成的回调
  final PlatformViewCreatedCallback onPlatformViewCreated;
  /// hit测试期间的行为
  final PlatformViewHitTestBehavior hitTestBehavior;
  /// 视图的文本方向
  final TextDirection layoutDirection;
  /// 传给iOS视图的参数,在Android视图构造的时候使用
  final dynamic creationParams;
  /// 对creationParams参数传递时进行的编码规则,如果creationParams不为null,该值必须不为null
  final MessageCodec<dynamic> creationParamsCodec;
  /// 用于处理时间冲突,对时间进行分发管理相关操作
  final Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers;

  @override
  State<UiKitView> createState() => _UiKitViewState();
}

需要使用Xcode进行开发,用Android Studio打开创建好的Flutter项目,在Android Studio顶部菜单Tools->Flutter->Open iOS module in Xcode,点击即可打开一个iOS项目

第一步,在Runner目录下创建iOS View,此View继承FlutterPlatformView


import Foundation
import Flutter

class CustomFlutterView:NSObject,  FlutterPlatformView {
    
    let label = UILabel()
    
    init(_ frame: CGRect, viewID: Int64, params: Any?, messenger: FlutterBinaryMessenger) {
        super.init()
        if(params is NSDictionary){
            let dict = params as! NSDictionary
            label.text = "\(dict.value(forKey: "init") as? String ?? "")点击发送数据给Flutter"
        }
        
        let methodChannel = FlutterMethodChannel(name: "com.mufeng.flutter_native_view", binaryMessenger: messenger)
        methodChannel.setMethodCallHandler {(call, result) in
            if(call.method == "updateText"){
                if let dict = call.arguments as? Dictionary<String, Any>{
                    let author: String = dict["author"] as? String ?? ""
                    self.label.text = "Hello, \(author), 点击发送数据给Flutter"
                }
            }
        }
        
        label.addOnClick{ (view) in
            var arguments = Dictionary<String, Any>()
            arguments["text"] = "CustomFlutterView_\(viewID)"
            methodChannel.invokeMethod("sendMsgToFlutter", arguments: arguments)
        }
    }
    
    func view() -> UIView {
        return label
    }
    
}

第二步,创建CustomFlutterViewFactory:


import Foundation
import Flutter

class CustomFlutterViewFactory: NSObject, FlutterPlatformViewFactory {
    var messenger: FlutterBinaryMessenger
    
    init(messenger: FlutterBinaryMessenger) {
        self.messenger = messenger
        super.init()
    }
    
    func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments params: Any?) -> FlutterPlatformView{
        return CustomFlutterView(frame, viewID: viewId, params: params, messenger: messenger)
    }
    
    func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol {
            return FlutterStandardMessageCodec.sharedInstance()
        }
}

第三步,在AppDelegate中注册:

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    
  let VIEW_TYPE_ID: String = "com.mufeng.flutter_native_view/custom_platform_view"
    
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    
    let registrar: FlutterPluginRegistrar = self.registrar(forPlugin: VIEW_TYPE_ID)!
    let factory = CustomFlutterViewFactory(messenger: registrar.messenger())
    registrar.register(factory, withId: VIEW_TYPE_ID)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

注意:VIEW_TYPE_ID 这个字符串需要和Flutter端保持一致

第四步,在Flutter中调用


class _MyHomePageState extends State<MyHomePage> {


  static const platform =
  const MethodChannel('com.mufeng.flutter_native_view');

  String result;

  @override
  void initState() {
    super.initState();
    platform.setMethodCallHandler((call) {
      setState(() {
        result = call.arguments['text'];
      });
      print("接收到Native传递的数据: ${call.arguments['text']}");
      return;
    });
  }


  @override
  Widget build(BuildContext context) {
    Widget platformView() {
      if (defaultTargetPlatform == TargetPlatform.android) {
        return AndroidView(
          viewType: "com.mufeng.flutter_native_view/custom_platform_view",
          creationParams: {'init': '来自Flutter传递的初始化参数'},
          creationParamsCodec: StandardMessageCodec(),
          onPlatformViewCreated: (viewId) {
            print('View 创建完成; ViewId: $viewId');
          },
        );
      }else if(defaultTargetPlatform == TargetPlatform.android){
        return UiKitView(
          viewType: "com.mufeng.flutter_native_view/custom_platform_view",
          creationParams: {'init': '来自Flutter传递的初始化参数'},
          creationParamsCodec: StandardMessageCodec(),
          onPlatformViewCreated: (viewId) {
            print('View 创建完成; ViewId: $viewId');
          },
        );
      }else{
        return Text('暂不支持的平台类型');
      }
    }
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Platform View',
          style: TextStyle(
              color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
        ),
        centerTitle: true,
      ),
      body: Column(
        children: [
          TextButton(onPressed: () {
            platform.invokeMethod('updateText', {'author': 'MuFeng'});
          }, child: Text('传递参数给原生View')),
          Text(result??'等待Native发送的数据'),
          Expanded(child: platformView()),
        ],
      ),
    );
  }
}

查看在iOS中的运行效果:


image

image

image

本文代码地址

https://github.com/hanlin19900610/flutter-action/tree/main/flutter-native/flutter_native_view

以上只是Platform View的简单的使用,更加详细的使用,请参考一下资料:
嵌入原生View-Android
嵌入原生View-IOS
在Flutter中嵌入Native组件的正确姿势
万万没想到——Flutter外接纹理

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,772评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,458评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,610评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,640评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,657评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,590评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,962评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,631评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,870评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,611评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,704评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,386评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,969评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,944评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,179评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,742评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,440评论 2 342

推荐阅读更多精彩内容