【问题标题】:How to keep multiple method channels in same flutter application如何在同一个颤振应用程序中保留多个方法通道
【发布时间】:2020-06-24 06:04:06
【问题描述】:

我知道我可以通过dart代码访问多个MethodChannel,但是我应该如何在平台代码上实现多个MethodChannel而不使用多个插件。

我已经尝试过搜索,但每个文档和文章都只显示每个插件的单个方法通道

override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "org.my.application/channel")
    channel.setMethodCallHandler(this);
  }

在上述 Flutter 插件的onAttachedToEngine 中,我创建了一个名为“org.my.application/channel”的单个频道,我怎样才能在同一个插件中制作更多内容?

我现在唯一的选择是在多个插件中使用划分不同方法通道的实现。

有没有办法将它们保存在一个插件中?

【问题讨论】:

  • 多个MethodChannels有什么问题?您只需使用不同的String name,就可以拥有任意数量的频道
  • 我不知道如何在一个包中创建多个MethodChannel。
  • 在调用MethodChannel构造函数时使用不同的String name
  • 我可以通过dart端访问多个通道但是如何在不使用多个包的情况下在Platform端实现多个方法通道
  • 所以使用channel1 = MethodChannel(...); channel1.setMethodCallHandler(handler1); channel2 = MethodChannel(...); channel2.setMethodCallHandler(handler2); - 多通道和多处理程序有什么问题?

标签: flutter dart


【解决方案1】:

是的,你可以。基本上,只需创建一个新的 MethodChannel 并设置它的MethodCallHandler

override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    final MethodChannel methodChannel = new MethodChannel(messenger, yourPackageName, codec);
    channel.setMethodCallHandler(this);
    
    // Just create a MethodChannel with a different channel name.
    final MethodChannel specialMethodChannel = new MethodChannel(messenger, yourPackageName + ".specialMethodChannel", codec);
    specialMethodChannel.setMethodCallHandler(this);
  }

您也可以创建一个实现 MethodCallHandler 接口的新类,而不是在调用 setMethodCallHandler(this) 时共享相同的方法调用处理程序 (this)。


我在查看如何跨应用程序的不同线程或部分创建对应于相同通道名称的多个 MethodChannel 时发现了这一点。这是因为每个 MethodChannel 只能在一个线程中使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多