Flutter FCM onMessage 在听时不起作用

问题描述

我有这个问题......发送通知时,在监听 onMessage 时的回调没有被调用,而通知显示在设备上。

初始化时

FirebaseMessaging.instance.requestPermission(
    sound: true,badge: true,alert: true,provisional: false,);

String? token = await _firebaseMessaging.getToken();


FirebaseMessaging.instance.setForegroundNotificationPresentationoptions(
    alert: true,sound: true,);

在听

 FirebaseMessaging.onMessage.handleError((error) {
      print("Erorrrrrr : ${error.toString()}");
    }).listen((event) {
      print(event.data);
      _showNotification({
        "title": event.notification?.title ?? "","body": event.notification?.body ?? "",});
    });

发布规范:
sdk: ">=2.12.0 firebase_core:^1.0.0
firebase_messaging:^9.0.0

医生总结

Doctor summary (to see all details,run Flutter doctor -v):
[✓] Flutter (Channel master,2.1.0-13.0.pre.214,on macOS 11.2.3 20D91 darwin-x64,locale en-EG)
[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    ! Some Android licenses not accepted.  To resolve this,run: Flutter doctor --android-licenses
[✓] Xcode - develop for iOS and macOS
[✓] Chrome - develop for the web
[✓] Android Studio (version 4.1)
[✓] Connected device

解决方法

如果您从 firebase 控制台发送通知并尝试打印
打印(事件数据); 这将引发异常,因为在这种情况下数据将为空,您必须调用 event.title 或 body