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

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

AndroidView

class MyFlutterView(context: Context) : PlatformView {
    override fun getView(): View {
        TODO("Not yet implemented")
    }

    override fun dispose() {
        TODO("Not yet implemented")
    }
}
  • getView :返回要嵌入 Flutter 层次结构的Android View
  • dispose:释放此View时调用,此方法调用后 View 不可用,此方法需要清除所有对象引用,否则会造成内存泄漏。
class MyFlutterView(context: Context,messenger: BinaryMessenger,viewId: Int,args: Map<String,Any>?) : PlatformView {

    val textView: TextView = TextView(context)

    init {
        textView.text = "我是Android View"
    }

    override fun getView(): View {

        return textView
    }

    override fun dispose() {
        TODO("Not yet implemented")
    }
}
  • messenger:用于消息传递,后面介绍 Flutter 与 原生通信时用到此参数。
  • viewId:View 生成时会分配一个唯一 ID。
  • args:Flutter 传递的初始化参数。

注册PlatformView

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

    override fun create(context: Context,args: Any?): PlatformView {
        val flutterView = MyFlutterView(context,messenger,viewId,args as Map<String,Any>?)
        return flutterView
    }

}
class MyPlugin : FlutterPlugin {

    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        val messenger: BinaryMessenger = binding.binaryMessenger
        binding
                .platformViewRegistry
                .registerViewFactory(
                        "plugins.flutter.io/custom_platform_view",MyFlutterViewFactory(messenger))
    }

    companion object {
        @JvmStatic
        fun registerWith(registrar: PluginRegistry.Registrar) {
            registrar
                    .platformViewRegistry()
                    .registerViewFactory(
                            "plugins.flutter.io/custom_platform_view",MyFlutterViewFactory(registrar.messenger()))
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {

    }
}
class MainActivity : FlutterActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        flutterEngine.plugins.add(MyPlugin())
    }
}
public class CustomPlatformViewPlugin : FlutterPlugin,MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(),"custom_platform_view")
        channel.setMethodCallHandler(this)

        val messenger: BinaryMessenger = flutterPluginBinding.binaryMessenger
        flutterPluginBinding
                .platformViewRegistry
                .registerViewFactory(
                        "plugins.flutter.io/custom_platform_view",MyFlutterViewFactory(messenger))

    }

    // This static function is optional and equivalent to onAttachedToEngine. It supports the old
    // pre-Flutter-1.12 Android projects. You are encouraged to continue supporting
    // plugin registration via this function while apps migrate to use the new Android APIs
    // post-flutter-1.12 via https://flutter.dev/go/android-project-migration.
    //
    // It is encouraged to share logic between onAttachedToEngine and registerWith to keep
    // them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called
    // depending on the user's project. onAttachedToEngine or registerWith must both be defined
    // in the same class.
    companion object {
        @JvmStatic
        fun registerWith(registrar: Registrar) {
            val channel = MethodChannel(registrar.messenger(),"custom_platform_view")
            channel.setMethodCallHandler(CustomPlatformViewPlugin())

            registrar
                    .platformViewRegistry()
                    .registerViewFactory(
                            "plugins.flutter.io/custom_platform_view",MyFlutterViewFactory(registrar.messenger()))
        }
    }

    override fun onMethodCall(@NonNull call: MethodCall,@NonNull result: Result) {
        if (call.method == "getPlatformVersion") {
            result.success("Android ${android.os.Build.VERSION.RELEASE}")
        } else {
            result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }
}

嵌入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',);
      }
    }
    return Scaffold(
      appBar: AppBar(),body: Center(
        child: platformView(),),);
  }
}

设置初始化参数

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

    val textView: TextView = TextView(context)

    init {
        args?.also {
            textView.text = it["text"] as String
        }
    }

    override fun getView(): View {

        return textView
    }

    override fun dispose() {
        TODO("Not yet implemented")
    }
}

Flutter 向 Android 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',);
      }
    }

    return Scaffold(
      appBar: AppBar(),body: Column(children: [
        RaisedButton(
          child: Text('传递参数给原生View'),onPressed: () {
            platform.invokeMethod('setText',{'name': 'laomeng','age': 18});
          },Expanded(child: platformView()),]),);
  }
}
class MyFlutterView(context: Context,Any>?) : PlatformView,MethodChannel.MethodCallHandler {

    val textView: TextView = TextView(context)
    private var methodChannel: MethodChannel

    init {
        args?.also {
            textView.text = it["text"] as String
        }
        methodChannel = MethodChannel(messenger,"com.flutter.guide.MyFlutterView")
        methodChannel.setMethodCallHandler(this)
    }

    override fun getView(): View {

        return textView
    }

    override fun dispose() {
        methodChannel.setMethodCallHandler(null)
    }

    override fun onMethodCall(call: MethodCall,result: MethodChannel.Result) {
        if (call.method == "setText") {
            val name = call.argument("name") as String?
            val age = call.argument("age") as Int?

            textView.text = "hello,$name,年龄:$age"
        } else {
            result.notImplemented()
        }
    }
}

Flutter 向 Android View 获取消息

override fun onMethodCall(call: MethodCall,result: MethodChannel.Result) {
    if (call.method == "setText") {
        val name = call.argument("name") as String?
        val age = call.argument("age") as Int?
        textView.text = "hello,年龄:$age"
    } else if (call.method == "getData") {
        val name = call.argument("name") as String?
        val age = call.argument("age") as Int?

        var map = mapOf("name" to "hello,$name","age" to "$age"
        )
        result.success(map)
    } else {
        result.notImplemented()
    }
}
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
class MyFlutterView(context: Context,"com.flutter.guide.MyFlutterView_$viewId")
        methodChannel.setMethodCallHandler(this)
    }
  ...
}
var platforms = [];

AndroidView(
  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_68282.html