Flutter中使用Android的原生View

添加原生组件的流程基本上可以描述为:

1 android 端实现原生组件PlatformView提供原生view
2 android 端创建PlatformViewFactory用于生成PlatformView
3 android 端创建FlutterPlugin用于注册原生组件
4 flutter 平台嵌入 原生view

首先创建一个Flutter项目,创建完成后单独打开Flutter中的android项目,在其中新建类LinkNativeView实现PlatFormView方法,代码如下:

class LinkNativeView(context: Context?) : PlatformView {

    private val showTextView:TextView = TextView(context)

    init {
        showTextView.text = "hello This is android view"
    }
    override fun getView(): View {
        return showTextView
    }

    override fun dispose() {

    }
}

这个时候android原生View类就创建好了,紧接着新建类LinkNativeViewFactory继承PlatformViewFactory,代码如下:

class LinkNativeViewFactory(val messenger:BinaryMessenger): PlatformViewFactory(StandardMessageCodec.INSTANCE) {
    override fun create(context: Context?, viewId: Int, args: Any?): PlatformView {
        val linkNativeView:LinkNativeView = LinkNativeView(context)
        return  linkNativeView
    }
}

接着我们在Activity中引用就行了,代码如下:

class MainActivity: FlutterActivity() {

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        GeneratedPluginRegistrant.registerWith(flutterEngine)
        val registry = flutterEngine.platformViewsController.registry
        registry.registerViewFactory("android_show_view",LinkNativeViewFactory(flutterEngine.dartExecutor))
    }
}

这样原生端的代码就写完了,接下来我们打开Flutter项目,在需要引入原生View的地方添加代码:

Widget getNativeView(){
    var view = Container(
      height: 200,
      child: AndroidView(viewType: 'android_show_view'),
    );

    return view;
  }

然后在build方法中添加就可以了,这里需要注意一下,项目中的Flutter版本是2.12.0 ,在Flutter端引入原生组件时需要给AndroidView套一个盒子组件否则高度无法确定运行出来效果会报超出警告。
此时原生View已经成功显示在Flutter中,我们此时需要在Flutter与原生View中传输数据,修改代码,在flutter代码中添加:

child: AndroidView(
          viewType: 'android_show_view',
          creationParams: {'text':'this is flutter to native data'},
          creationParamsCodec: const StandardMessageCodec(),
      ),
    );

这样Flutter端代码就修改完了,在看原生代码,修改LinkNativeViewFactory里面代码:

override fun create(context: Context?, viewId: Int, args: Any?): PlatformView {
        var params:Map = args as Map
        val linkNativeView:LinkNativeView = LinkNativeView(context,messenger,params,viewId)
        return  linkNativeView
    }

然后修改LinkNativeView的代码:

init {
        val viewText = params["text"] as String
        showTextView.text = viewText
    }

此时运行代码就可以看到结果了。

你可能感兴趣的:(Flutter中使用Android的原生View)