首页 > 解决方案 > 发送图像作为 Flutter 平台通道方法的参数

问题描述

我正在构建一个 Flutter 应用程序,对于我正在使用的其中一个 API,它不支持 Flutter,只有 Android 和 iOS。我对此的解决方案是使用平台通道,但我如何将图像作为参数传递?

为了进一步解释,我从ImagePicker().getImagedart 文件中的图库中选择一个图像,我想将选择的图像发送到 Kotlin 文件中的方法,该方法将在其末尾对图像执行某些操作并返回一个字符串。

查看文档后,我能够制作这样的频道:

static const platform = const MethodChannel('app.dev/channel'); 
final string result = await platform.invokeMethod('returnStringfromImage');

在 Kotlin 文件中:

 private val CHANNEL = "app.dev/channel"

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
            // Note: this method is invoked on the main thread.
            call, result ->
            if (call.method == "returnStringfromImage") {
                val return = returnStringfromImage(call.arguments)
                
            }

            else {
                result.notImplemented()
            }
        }

    }

我将如何发送图像,并将其作为 returnStringfromImage() 方法的参数传递?谢谢!

标签: androidflutterdartmobile-developmentflutter-platform-channel

解决方案


您需要将拾取的图像转换为任何这些支持的类型,最有可能作为字节(Uint8list)发送到平台端。

ImagePicker 将返回 a File,因此您可以调用readAsBytes它来获取Uint8list。然后你可以通过invokeMethod.


推荐阅读