I'm trying to port Zendesk Native SDK for Android in Flutter using MethodChannel and Kotlin as my language choice.

It works when I use the Kotlin code directly inside the project which is

class MainActivity : FlutterActivity() {

  // others code are hidden

  private fun initialize(call: MethodCall, result: Result) {
    val url: String = call.argument("url")!!
    val appId: String = call.argument("appId")!!
    val clientId: String = call.argument("clientId")!!

    Zendesk.INSTANCE.init(this, url, appId, clientId)
    val identity = AnonymousIdentity()
    Zendesk.INSTANCE.setIdentity(identity)
    Support.INSTANCE.init(Zendesk.INSTANCE)

    RequestListActivity.builder().show(this)
    result.success(true)
  }
}

The this is referring to Activity which I guess FlutterApplication already has inside of it, but when I try to make the standalone plugin thing is a little bit different. I need to implement ActivityAware to get the activity (Get activity reference in flutter plugin).

https://github.com/flutter/flutter/wiki/Experimental:-Create-Flutter-Plugin

(Optional) If your plugin needs an Activity reference, also implement ActivityAware.

public class ZendeskPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
  private lateinit var activityBinding: ActivityPluginBinding

  // I can get ActivityPluginBinding from this method
  override fun onAttachedToActivity(@NonNull binding: ActivityPluginBinding) {
    activityBinding = binding
  }

  private fun initialize(call: MethodCall, result: Result) {
    activityBinding?.activity?.let {
      val appId: String = call.argument("appId")!!
      val clientId: String = call.argument("clientId")!!
      val url: String = call.argument("url")!!

      Zendesk.INSTANCE.init(it, url, appId, clientId)
      val identity = AnonymousIdentity()
      Zendesk.INSTANCE.setIdentity(identity)
      Support.INSTANCE.init(Zendesk.INSTANCE)

      RequestListActivity.builder().show(it)
      result.success(true)
      return
    }

    result.error("INITIALIZE_FAILED", "Failed to initialize", null)
  }
}

I tried to call initialize from dart and actually it runs but onAttachedToActivity seems is never be invoked and makes activityBinding is never be initialized so the code fails and result.error.

How do I get activity inside FlutterPlugin class? Thank you


Solution 1: David Araujo

Probably the problem is the call of the setMethodCallHandler in the onAttachedToEngine

Look more here