kotlin - 从 Dart 向 Kotlin 发送回调函数
问题描述
我正在使用颤振通道与我的应用程序的 android (Kotlin) 本机端进行通信。但我不知道是否可以从 Dart 向 Kotlin 发送回调(在这种情况下是一个只接受字符串作为参数的函数)?如果是,我应该如何输入?
比方说,我有这个飞镖功能
void _acceptEngineOutput(String output){
}
还有这个 Kotlin 函数
fun readEngineOutput(callback) {
while(process.isAlive) {
line = outputBuffer.readLine()
if (line != null && line.length > 0) callback(line)
}
}
应该如何键入回调参数,以便我可以传入 _acceptOutput 函数?
这是我的 MainActivity 类,现在,我只是想念 sendEngineOutput 方法中的回调类型。
package com.loloof64.chess_exercise_manager_flutter
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant
import io.flutter.plugin.common.MethodChannel
import com.kalab.chess.enginesupport.ChessEngineResolver
import com.kalab.chess.enginesupport.ChessEngine
import java.io.File
class MainActivity: FlutterActivity() {
private val CHANNEL = "loloof64.chess_utils/engine_discovery"
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine)
MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
.setMethodCallHandler(
{ call, result ->
if (call.method.equals("copyAllEnginesToAppDir")) {
copyAllEnginesToAppDir()
result.success(1)
}
else if (call.method.equals("setEngineOutputListener")) {
setEngineOutputListener(call.arguments)
result.success(output)
}
else {
result.notImplemented();
}
}
)
}
private fun setEngineOutputListener(callback) {
}
}
解决方案
正如@pskink 让我通知的那样:我必须setMethodCallHandler
在我的 Flutter 代码中使用。
- 在我需要执行回调的 MainActivity 中,我调用了类似
methodChannel?.invokeMethod("processEngineOutput", line)
. 这里 processEngineOutput 是从我的 Flutter 代码中捕获的引用 - 在我的 Flutter 代码中,在构建 Wiget 时,我为平台通信设置了回调。例如
@override
Widget build(BuildContext context) {
platform.setMethodCallHandler(_processEngineOutput); // <---- HERE !!!! --->
return Scaffold(
appBar: AppBar(
title: Text('Chess exercises manager'),
),
body: Center(
child: ChessBoard(
MediaQuery.of(context).size.width
),
),
);
}
- 我将回调定义
_processEngineOutput
为未来,并检查方法调用是否正确
Future<void> _processEngineOutput(MethodCall call) async {
if (call.method != 'processEngineOutput') return;
var line = call.arguments;
print(line);
}
推荐阅读
- graph-databases - 无法再连接到 Neptune
- python - 在 pytorch 中创建数据集时如何关闭某些类?
- javascript - 关闭jQuery中的上一个下拉菜单不起作用
- python - AWS lambda 与 python asyncio。事件循环关闭问题?
- reactjs - 按需加载翻译文件
- html - rendersubtree invisible vs hidden or display none
- video - 具有 H.264 的 mpeg-4 容器所需的最小 Atom/Box 集(一个流,渐进式视频,无音频)
- css - 您如何为元素设置动画以使其从页面顶部滑入。元素在带有网格的页面中居中
- certificate - 如何或在哪里下载我的 AWS IoT 根 CA?
- r - 如何在单变量动物园系列中添加一列?