Flutter与Swift MethodChannel交互崩溃:NSNull转NSString失败
解决Flutter MethodChannel iOS端崩溃问题
问题场景
在Flutter应用中通过MethodChannel调用iOS原生方法时触发崩溃,错误提示为Could not cast value of type 'NSNull' (0x221756b90) to 'NSString' (0x221753d80)。
Flutter端代码
void startNotifications() async { try { var methodChannel = MethodChannel('com.test/notificationsChannel'); await _methodChannel.invokeMethod('startNotification'); } catch (_) {} }
Swift端原代码(崩溃版本)
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController let notificationChannel = FlutterMethodChannel(name: "com.test/notificationsChannel", binaryMessenger: controller.binaryMessenger) notificationChannel.setMethodCallHandler({ (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in switch(call.method){ case "startNotification": break; default: return } })
崩溃错误日志
Could not cast value of type 'NSNull' (0x221756b90) to 'NSString' (0x221753d80). * thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGABRT frame #0: 0x00000001fe71c2f4 libsystem_kernel.dylib`__pthread_kill + 8 libsystem_kernel.dylib`: -> 0x1fe71c2f4 <+8>: b.lo 0x1fe71c310 ; <+36> 0x1fe71c2f8 <+12>: stp x29, x30, [sp, #-0x10]! 0x1fe71c2fc <+16>: mov x29, sp 0x1fe71c300 <+20>: bl 0x1fe717cd4 ; cerror_nocancel Target 0: (Time4BUS) stopped.
解决方案
崩溃核心原因是Swift端未调用FlutterResult回调函数。Flutter端通过invokeMethod发起调用后会等待原生返回结果,若原生未主动触发result,底层会默认返回NSNull,跨平台数据转换时会触发类型强制转换错误。
修改Swift端代码,确保每个方法分支都调用result:
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController let notificationChannel = FlutterMethodChannel(name: "com.test/notificationsChannel", binaryMessenger: controller.binaryMessenger) notificationChannel.setMethodCallHandler({ (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in switch(call.method){ case "startNotification": // 执行通知业务逻辑后调用result,无返回数据则传nil result(nil) default: // 处理未实现的方法,返回标准错误标记 result(FlutterMethodNotImplemented) } })
关键修改点:
- 在
startNotification分支中,完成业务逻辑后必须调用result(即使无需返回数据,也需传nil) - 在
default分支中,返回FlutterMethodNotImplemented,明确告知Flutter端该方法未实现
内容的提问来源于stack exchange,提问作者Dawid Długosz
相关产品推荐
相关产品推荐

