我正在实现MethodChannel将值从Flutter端传递到Kotlin Android本机代码。我遵循了这两个教程,他们做的和我复制的完全一样:https://youtu.be/j0cy_Z6IG_c &https://youtu.be/XwwsI8vAHtk
我在main中的MethodChannel实现。dart [Flutter]如下:
class _MyHomePageState extends State<MyHomePage> {
static const frequencyChannel =
MethodChannel('com.somdipdey.eoptomizer/frequency');
...
...
Future setFrequencyLevelCPU0Max() async {
var sendMapMaxCPUFreq = <String, String>{
"LITTLECPUMaxFreq": _LITTLECPUFreq.text.toString()
};
final String frequencyLevelCPU0Max = await frequencyChannel.invokeMethod(
'setFrequencyLevelCPU0Max', sendMapMaxCPUFreq);
}
}
在Kotlin端,在MainActivity中。MethodChannel实现的代码如下:
class MainActivity: FlutterActivity() {
private val OPTIMIZATION_CHANNEL = "com.somdipdey.eoptomizer/frequency"
private lateinit var channel: MethodChannel
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, OPTIMIZATION_CHANNEL)
channel.setMethodCallHandler { call, result ->
if (call.method == "setFrequencyLevelCPU0Max" || call.method == "setFrequencyLevelCPU0Min" || call.method == "setFrequencyLevelCPU4Min") {
var arguments = call.arguments() as Map<String,String>
var LITTLECPUMaxFreq = arguments["LITTLECPUMaxFreq"].toString() ?: "1766400"
setFrequencyLevelCPU0Max(LITTLECPUMaxFreq)
result.success("Optimizing frequencies on CPU0")
}
}
}
}
当我尝试构建/运行项目时,我在Kotlin端得到以下错误:
MainActivity。kt:(27,38):类型不匹配:推断类型是Map<String;String> ?但是Map<String,>预计
这个错误发生在以下代码行:
var arguments = call.arguments() as Map<String,String>
如何解决这个问题?
Kotlin编译器不能假设call.arguments()
返回非空值,因此正确的类型是Map<String,String>?
,这意味着您必须将其强制转换为该值。下一行也需要修改,以处理一个可能为空的参数值:
var arguments = call.arguments() as Map<String,String>?
var LITTLECPUMaxFreq = arguments?.get("LITTLECPUMaxFreq")?.toString() ?: "1766400"