首页 > 解决方案 > 是否可以在 Flutter 中不添加 Android 插件的情况下使用 PlatformView?

问题描述

我有一个PlatformView用于在我的 Flutter 应用程序中显示地图的工具。平台视图位于插件中,因此它可以访问PluginRegistry并可以使用方法注册平台视图PlatformViewRegistry platformViewRegistry()

但是,我想将它从插件移动到主项目,以便将所有内容保存在一个项目中。

这可能吗,在这种情况下我应该如何访问platformViewRegistry

标签: flutterflutter-plugin

解决方案


我是这样做的,使用flutterEngine您在主要活动中获得的参考来获取注册表:

在你的主要活动中

 override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine)
        YourPlugin.registerWith(flutterEngine)
 }

你的插件将是

import io.flutter.embedding.engine.FlutterEngine

object YourPlugin{
    fun registerWith(engine: FlutterEngine) {
        engine
            .platformViewsController.registry
            .registerViewFactory(
                YourView.VIEW_NAME, YourViewFactory(engine.dartExecutor.binaryMessenger))
    }
}

终于有了这样的工厂

import android.content.Context
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.StandardMessageCodec
import io.flutter.plugin.platform.PlatformView
import io.flutter.plugin.platform.PlatformViewFactory

class YourViewFactory(private val messenger: BinaryMessenger) : PlatformViewFactory(StandardMessageCodec.INSTANCE) {

    override fun create(context: Context, id: Int, o: Any?): PlatformView {
        return YourView(context, messenger, id)
    }
}

推荐阅读