首页 > 解决方案 > 从 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) {

    }

}

标签: kotlinflutterdart

解决方案


正如@pskink 让我通知的那样:我必须setMethodCallHandler在我的 Flutter 代码中使用。

  1. 在我需要执行回调的 MainActivity 中,我调用了类似methodChannel?.invokeMethod("processEngineOutput", line). 这里 processEngineOutput 是从我的 Flutter 代码中捕获的引用
  2. 在我的 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
        ),
      ),
    );
  }
  1. 我将回调定义_processEngineOutput为未来,并检查方法调用是否正确
Future<void> _processEngineOutput(MethodCall call) async {
    if (call.method != 'processEngineOutput') return;
    var line = call.arguments;
    print(line);
  }

推荐阅读