尝试从 Flutter 中的 Registar 获取上下文时出现 Kotlin 空指针异常

Kotlin null pointer exception when trying to get context from Registar in Flutter

我正在尝试创建一个使用原生 Android sdk

的 Flutter 插件

我能够编译 sdk 的 .aar 库并在项目中使用它们,但 sdk 要求我获取主要内容的上下文 activity

这是我得到的错误

E/MethodChannel#mychart_plugin(16277): Failed to handle method call
E/MethodChannel#mychart_plugin(16277): kotlin.KotlinNullPointerException
E/MethodChannel#mychart_plugin(16277):  at org.ccf.flutter.plugin.mychart_plugin.MychartPlugin.getContext(MychartPlugin.kt:79)
E/MethodChannel#mychart_plugin(16277):  at epic.mychart.android.library.api.authentication.WPAPIAuthentication.getContext(WPAPIAuthentication.java:564)
E/MethodChannel#mychart_plugin(16277):  at epic.mychart.android.library.prelogin.AuthenticationService.libraryLogin(AuthenticationService.java:461)
E/MethodChannel#mychart_plugin(16277):  at epic.mychart.android.library.api.authentication.WPAPIAuthentication.login(WPAPIAuthentication.java:411)
E/MethodChannel#mychart_plugin(16277):  at org.ccf.flutter.plugin.mychart_plugin.MychartPlugin.onMethodCall(MychartPlugin.kt:42)
E/MethodChannel#mychart_plugin(16277):  at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:201)
E/MethodChannel#mychart_plugin(16277):  at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:88)
E/MethodChannel#mychart_plugin(16277):  at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:219)
E/MethodChannel#mychart_plugin(16277):  at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#mychart_plugin(16277):  at android.os.MessageQueue.next(MessageQueue.java:325)
E/MethodChannel#mychart_plugin(16277):  at android.os.Looper.loop(Looper.java:142)
E/MethodChannel#mychart_plugin(16277):  at android.app.ActivityThread.main(ActivityThread.java:6541)
E/MethodChannel#mychart_plugin(16277):  at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#mychart_plugin(16277):  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
E/MethodChannel#mychart_plugin(16277):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

这是我获取上下文的代码

class MychartPlugin: MethodCallHandler, WPAPIAuthentication.IWPOnLoginListener {
private var registrar: PluginRegistry.Registrar? = null
private val LOGIN_REQUEST_CODE = 9876

fun MychartPlugin(registrar: PluginRegistry.Registrar) {
  this.registrar = registrar
}
companion object {
  @JvmStatic
  fun registerWith(registrar: Registrar) {
    val channel = MethodChannel(registrar.messenger(), "mychart_plugin")
    channel.setMethodCallHandler(MychartPlugin())
  }
}

override fun onMethodCall(call: MethodCall, result: Result) {
  if (call.method == "getPlatformVersion") {
    result.success("Android ${android.os.Build.VERSION.RELEASE}")
  } else if (call.method == "MyChartSdkLogin") {
  WPAPIAuthentication.login(this, "TURKJ123", "TurkJ123", LOGIN_REQUEST_CODE)
    result.success("called MyChartSdkLogin")
  }  else {
    result.notImplemented()
  }
}


override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
  // super.onActivityResult(requestCode, resultCode, data)
  if (requestCode == LOGIN_REQUEST_CODE) {
    if (resultCode == Activity.RESULT_OK) {
      // login successful
      Log.i("LoginFragment", "OK")

    } else {
      // login failed
      val result = WPAPIAuthentication.getLoginResult(data)
      Log.i("LoginFragment", result.toString())
      val errorMessage = result.getErrorMessage(getContext())
      if (!errorMessage.isEmpty()) {
        Toast.makeText(getContext(), errorMessage, Toast.LENGTH_LONG).show()
      }
    }
  }
}

override fun startActivityForResult(p0: Intent, p1: Int) {
  // super.startActivityForResult(p0, p1)
}

override fun getSupportFragmentManager(): FragmentManager {
  val act = registrar!!.activity() as FragmentActivity
  return act.getSupportFragmentManager()
}

override fun getContext(): Context {
  val cxt = registrar!!.context()
  return cxt
}

}

注意我从 sdk 覆盖的 override getContext() 方法,我认为对 registar 的上下文调用是我的 KotlinNullPointerException 来自

getContext 中你有 registrar!!registrar 是一个可以为 null 的字段,您将其初始化为 null 并且只能在您从未调用的方法中设置。请注意 fun MychartPlugin 不是构造函数,您可以将其称为

val plugin = MychartPlugin()
plugin.MychartPlugin(registrar)

但似乎没有任何理由首先使 registrar 可为空或可变。您可以更改为

class MychartPlugin(private val registrar: Registrar): ...

fun registerWith(registrar: Registrar) {
  val channel = MethodChannel(registrar.messenger(), "mychart_plugin")
  channel.setMethodCallHandler(MychartPlugin(registrar))
}