You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 22:03:15