I did a plugin in native code(Kotlin) and tried to use that in a Flutter application. I used a method channel for Flutter to native code communication and an event channel for native code to Flutter. Method channel communication is working properly, but event channel isn't.
FLUTTER:
// will execute this in initState
EventChannel _eventChannel = EventChannel("STREAM_CHANNEL");
_eventChannel.receiveBroadcastStream().map((event) => {
// some actions
})
// will execute this by button click (happens after widget got built)
result =
await MethodChannel("METHOD_CHANNEL").invokeMethod("functionToInvoke", {
// payload
})
KOTLIN:
class MainActivity: FlutterActivity() {
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
startEventChannel(flutterEngine)
startMethodChannel(flutterEngine.dartExecutor.binaryMessenger)
}
fun startMethodChannel(@NonNull flutterEngine: FlutterEngine) {
MethodChannel(flutterEngine.dartExecutor.binaryMessenger,
"METHOD_CHANNEL").setMethodCallHandler {
call, result -> when(call.method) {
"functionToInvoke" -> {
// some action
}
}
}
// method not called inspite of calling from configureFlutterEngine
fun startEventChannel(messenger: BinaryMessenger) {
eventChannel = EventChannel(messenger, "STREAM_CHANNEL");
eventChannel.setStreamHandler(
object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, eventSink: EventChannel.EventSink)
{
eventSink.success("success")
}
}
)
}
The startEventChannel
method is not even called but startMethodChannel
has been called and methods are registered properly.
There is no issue with the channel names (checked both sides).
Am I missing anything?