Flutter:onDidReceiveNotificationResponse参数类型不匹配报错
Flutter Local Notifications 回调更新错误解决方法
报错原因是参数类型不匹配:onDidReceiveNotificationResponse要求的回调类型是DidReceiveNotificationResponseCallback,它的参数是NotificationResponse对象,而你当前的_onSelectNotification函数接收的是String?类型,导致类型无法匹配。
修改后的代码
回调函数调整:
Future<void>? _onSelectNotification(NotificationResponse response) { // 从NotificationResponse中获取payload final String? payloadNotification = response.payload; if (kDebugMode) { print("Notification selected."); } WidgetsBinding.instance.addPostFrameCallback((_) { if (payloadNotification != null && payloadNotification.isNotEmpty) { if (kDebugMode) { print(payloadNotification); } // 保留原有的解析逻辑 // PushRequest.Message message = // PushRequest.Message.fromJson(jsonDecode(payloadNotification)); } }); return null; }
初始化代码无需修改:
flutterLocalNotificationsPlugin.initialize(initSettings, onDidReceiveNotificationResponse: _onSelectNotification);
关键修改点
- 回调参数类型从
String?改为NotificationResponse,适配插件新版本的回调规范 - 通过
response.payload获取原有的通知负载内容 - 返回类型从
Future<dynamic>?改为Future<void>?,严格匹配DidReceiveNotificationResponseCallback的定义
如果需要处理通知的其他信息(比如通知ID、触发的动作ID),可以直接从NotificationResponse对象中获取,例如response.id、response.actionId。
内容的提问来源于stack exchange,提问作者KingsGuardGT
相关产品推荐
相关产品推荐

