flutter和Android混編下出現“No implementation found for method xxxx on channel”錯誤

星空零語發表於2020-12-17

flutter和Android混編下出現“No implementation found for method xxxx on channel”錯誤

這個錯誤出現的原因是Plugin的方法沒有找到,也可能是Plugin本身就沒有註冊成功。

在混編情況下出現這個問題,很大概率是我們在網上查詢的資料中是這樣寫的。

import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant
class MainActivity: FlutterActivity() {
    private val flutterMethodChannelName = "flutterCallbackMethodChannel"
    var methodChannel_callFlutter: MethodChannel? = null
    @SuppressLint("NewApi")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        GeneratedPluginRegistrant.registerWith(FlutterEngine(this@MainActivity))
        methodChannel_callFlutter = MethodChannel(flutterView, flutterMethodChannelName)
    }
}

這個程式碼在flutter更新了FlutterActivity後就會導致這個問題,不能再引用io.flutter.app.FlutterActivity這個FlutterActivity,而應該改用io.flutter.embedding.android.FlutterActivity。同時,繼承自新版本FlutterActivity的MainActivity找不到flutterView這個方法,因此要改用getFlutterEngine().getDartExecutor().getBinaryMessenger()來代替。

程式碼改為:

import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant


class MainActivity: FlutterActivity() {
    private val flutterMethodChannelName = "flutterCallbackMethodChannel"
    var methodChannel_callFlutter: MethodChannel? = null

    @SuppressLint("NewApi")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        methodChannel_callFlutter = MethodChannel(flutterEngine!!.dartExecutor.binaryMessenger, flutterMethodChannelName)
    }

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
    }
}

參考文章
https://blog.csdn.net/qq_40928212/article/details/105545875
https://blog.csdn.net/oZhuiMeng123/article/details/98120505
https://blog.csdn.net/weixin_44160584/article/details/108244793

相關文章