在flutter中编写kotlin代码的configureFlutterEngine方法中的问题

Ali*_*iri 3 android gradle kotlin flutter

我想在 flutter 中编写特定于平台的代码,根据 flutter 文档,我们应该重写configureFlutterEngine方法,如下面的代码片段:

override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
    GeneratedPluginRegistrant.registerWith(flutterEngine)
    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
      call, result ->
      // Note: this method is invoked on the main thread.
      // TODO
    }
  }
Run Code Online (Sandbox Code Playgroud)

但是当我将flutterEngine传递给generatedPluginRegistrant.registerWith()时,它说:

类型不匹配:推断类型为 FlutterEngine,但为 PluginRegistry!预计

我已经检查了 github 中下面的链接,但没有找到任何适合我的解决方案。 https://github.com/flutter/flutter/issues/45231

这是用于编写特定于平台的代码的 flutter 文档的链接。 https://flutter.dev/docs/development/platform-integration/platform-channels?tab=android-channel-kotlin-tab#example-project

Ali*_*iri 5

我使用了onCreate()而不是configureFlutterEngine()方法,现在工作正常。

override fun onCreate(savedInstanceState: Bundle?) {
    GeneratedPluginRegistrant.registerWith(this)
    MethodChannel(flutterView, CHANNEL).setMethodCallHandler {
      call, result ->
      // Note: this method is invoked on the main thread.
      // TODO
    }
  }
Run Code Online (Sandbox Code Playgroud)

不要传递flutterEngine.dartExecutor.binaryMessengerMethodChannel,而是传递flutterView

  • 如何获取 FlutterView ?它还在 registerWith(this) 处给出错误 (4认同)

Zoh*_*Ali 5

这就是我在 kotlin 中使用它的方式

import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity: FlutterActivity() {
  private val CHANNEL = "samples.flutter.dev/battery"

  override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
      call, result ->
      // Note: this method is invoked on the main thread.
      // TODO
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

确保使用如图所示的相同导入。阅读文档