Flutter插件iOS端invokeMethod回调报错:Map与Future类型不匹配
问题排查:Flutter MethodChannel回调类型不匹配错误
问题现象
iOS端通过MethodChannel调用Flutter的retrieve_data方法时,参数能正常传递到Flutter,但回调收到FlutterError,错误提示:
_Map<Object?, Object?>类型不是Future<dynamic>的子类型
相关代码
iOS端调用代码
pluginChannel.invokeMethod("retrieve_data", arguments: ["selectedVehicleType": selectedVehicleType] as! Any) { (r: Any) in print("@@ result from retrieve_data method call is: \(r)") if let error = r as? FlutterError { print("error is : \n\(error.code), \n\(error.message)") } }
Flutter端MethodCallHandler代码
channel.setMethodCallHandler((call) { switch (call.method) { case 'retrieve_data': print( '## retrieve_data received in NativeScreenExample with args \n \(call.arguments), \n of type \(call.arguments.runtimeType)'); dynamic result = channel.invokeMethod('data_retrieved', 'arg').then((result) { print( '## data_retireved method invoked with result data from native: \(result)'); return result; }); break; default: } return call.arguments; });
错误原因
Flutter的setMethodCallHandler要求回调函数必须返回**Future<dynamic>类型**,用来向原生端返回方法调用的结果。但当前代码最后返回的是call.arguments——这是一个Map对象,不是Future类型,直接触发了类型不匹配错误。
另外,在retrieve_data分支中,你调用了channel.invokeMethod('data_retrieved')但没有将它的返回结果作为整个handler的返回值,等于白执行了这段逻辑。
修正方案
将handler改为异步函数,确保返回值始终是Future类型,同时正确返回data_retrieved调用的结果:
channel.setMethodCallHandler((call) async { switch (call.method) { case 'retrieve_data': print( '## retrieve_data received in NativeScreenExample with args \n \(call.arguments), \n of type \(call.arguments.runtimeType)'); // 等待data_retrieved方法的调用结果 final result = await channel.invokeMethod('data_retrieved', 'arg'); print( '## data_retireved method invoked with result data from native: \(result)'); // 将结果返回给iOS端 return result; default: // 默认分支返回空Future,避免未匹配方法触发错误 return Future.value(null); } });
修正说明
- 用
async修饰回调函数,让其自动返回Future类型 - 在
retrieve_data分支使用await等待invokeMethod的异步结果,并将该结果返回给iOS端 - 默认分支返回
Future.value(null),确保所有未匹配的方法调用都返回合法的Future对象
内容的提问来源于stack exchange,提问作者Vincenzo
相关产品推荐
相关产品推荐

