Flutter方法频道和Facebook AppEventLogger

时间:2019-06-05 13:33:02

标签: android facebook flutter

我试图在onTap事件中从flutter调用一个函数,并将一些参数传递给本机android。请注意,我是一名PHP / JavaScript开发人员,我是Kotlin处女。

到目前为止,我已经设法使用以下方法做到这一点:

static const platform = const MethodChannel('foo.bar/example');

void _onTap() {
   var arguments = {'name': widget.recipe.name, 'id': widget.recipe.id.toString()};
   platform.invokeMethod('setPageView', arguments);
}

然后在MainActivity.kt中

class MainActivity : FlutterActivity() {
private val channel: String = "foo.bar/example"

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    GeneratedPluginRegistrant.registerWith(this)

    val logger = AppEventsLogger.newLogger(this)


    MethodChannel(flutterView, channel).setMethodCallHandler(MethodChannel.MethodCallHandler(fun(methodCall: MethodCall, result: MethodChannel.Result) {
        if (methodCall.method.equals("setPageView")) {
            val params = Bundle()

            params.putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, "recipe")
            params.putString(AppEventsConstants.EVENT_PARAM_CONTENT, methodCall.argument("recipe"))
            params.putString(AppEventsConstants.EVENT_PARAM_CONTENT_ID, methodCall.argument("id"))

            logger.logEvent(AppEventsConstants.EVENT_NAME_VIEWED_CONTENT, 0.0, params)

            logger.logEvent("pageView", 0.0, params)

            System.out.println("Called setPageView.")

        }
    }))
  }
}

问题是当我登录MethodCallHandler内部时,由于某种原因该事件未发送到Facebook。但是,如果我在

下记录了一些内容
val logger = AppEventsLogger.newLogger(this)

该事件已成功发送到Facebook。

MethodCallHandler内部的代码将执行,所以这不是问题。

知道我做错了什么吗?

谢谢

1 个答案:

答案 0 :(得分:0)

通过将MethodCallHandler的内容作为MainActivity类中的独立方法来解决

class MainActivity : FlutterActivity() {
    private val channel: String = "foo.bar/example"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        GeneratedPluginRegistrant.registerWith(this)

        MethodChannel(flutterView, channel).setMethodCallHandler(
                MethodChannel.MethodCallHandler(
                        fun(methodCall: MethodCall, result: MethodChannel.Result) {
                            if (methodCall.method.equals("setPageView")) {
                                logPageView(methodCall.argument("name"), methodCall.argument("id"))
                            }
                        }
                )
        )
    }

    fun logPageView(name: String?, id: String?) {
        val logger = AppEventsLogger.newLogger(this)
        val params = Bundle()

        params.putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, "recipe")
        params.putString(AppEventsConstants.EVENT_PARAM_CONTENT, name)
        params.putString(AppEventsConstants.EVENT_PARAM_CONTENT_ID, id)
        params.putString(AppEventsConstants.EVENT_PARAM_CURRENCY, "EUR")

        logger.logEvent(AppEventsConstants.EVENT_NAME_VIEWED_CONTENT, 0.0, params)
    }
}