Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override method onAttachedToEngine never gets called in FlutterPlugin

Tags:

kotlin

flutter

I'm trying to implement a flutter plugin but somehow the override function onAttachedToEngine never gets called. According to this doc

During the call to PluginRegistry.add(FlutterPlugin), the FlutterEngine will invoke onAttachedToEngine(FlutterPluginBinding) on the given FlutterPlugin.

but it is never invoked. One thing I have noticed though is that it actually invokes the first time you build and debug the app, and ceases after any rebuilds thereafter. Here is my code:

public class Plugin : FlutterPlugin, MethodCallHandler { 

override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
  channel = MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "flutter_plugin")
  channel.setMethodCallHandler(this)
  println("Engine is attached!")
}

companion object {
  @JvmStatic
  fun registerWith(registrar: Registrar) {
    val channel = MethodChannel(registrar.messenger(), "flutter_blockstack")
    channel.setMethodCallHandler(FlutterBlockstackPlugin())
    println("Registered!")
  }
}


override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
if (call.method == "getPlatformVersion") {
    result.success("Android ${android.os.Build.VERSION.RELEASE}")
  } else {
    result.notImplemented()
  }
}

}

like image 270
James Casia Avatar asked Mar 14 '26 15:03

James Casia


2 Answers

It is the expected behaviour.

Right after attaching to the FlutterEngine, this function gets called to set up a new MethodCallHandler. This is done either in onAttachedToEngine (AndroidX) or in registerWith (non AndroidX).

The function that actually gets called more than once is the onMethodCall, that gets called anytime you want from flutter with invokeMethod.

A hot restart or a hot reload will not trigger onAttachedToEngine, as actually, you haven't detached from the engine, so you need to deatach and reatach for it to be triggered.

I hope this clarification can help you!

like image 122
Francisco Javier Snchez Avatar answered Mar 17 '26 05:03

Francisco Javier Snchez


In my case, the log console on android just show on Logcat. Because I log on plugin not on example so many some flitter hidden it. But Logcat show all them. So I check the log of plugin on Logcat. Hope this information can help someone in my case.

like image 34
JackDao Avatar answered Mar 17 '26 04:03

JackDao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!