Home > front end >  Error: Type mismatch: inferred type is Map<String, String>? but Map<String, String> was
Error: Type mismatch: inferred type is Map<String, String>? but Map<String, String> was

Time:11-21

I am implementing MethodChannel to pass value from Flutter side to the Kotlin Android native code. I followed these two tutorials and they are doing exactly the same as I replicated: https://youtu.be/j0cy_Z6IG_c & https://youtu.be/XwwsI8vAHtk

My MethodChannel implementation in main.dart [Flutter] is as follows:

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);
  }
}

In Kotlin side, in MainActivity.kt the code for MethodChannel implementation is as follows:

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")
            }
        }
    }
}

When I try to build/run the project I get the following error in Kotlin side:

MainActivity.kt: (27, 38): Type mismatch: inferred type is Map<String, String>? but Map<String, String> was expected

This error is happening for the following line of code:

var arguments = call.arguments() as Map<String,String>

How can I resolve this issue?

CodePudding user response:

The Kotlin compiler can't assume that call.arguments() returns a non null value so the correct type is Map<String,String>? meaning you have to cast it to that. The next line needs to be changed as well to deal with a potentially null arguments value:

var arguments = call.arguments() as Map<String,String>?
var LITTLECPUMaxFreq = arguments?.get("LITTLECPUMaxFreq")?.toString() ?: "1766400"
  • Related