flutterpush-notificationfirebase-notifications

Flutter FCM onMessage doesn't work when listen to it


I have this problem ... when sending a notification, the callback while listening to onMessage, doesn't get called, while the notification shows up on the device.

On Initialize

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

String? token = await _firebaseMessaging.getToken();


FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
    alert: true,
    badge: true,
    sound: true,
  );

On Listen

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

Pubspec:
sdk: ">=2.12.0 <3.0.0",
firebase_core: ^1.0.0
firebase_messaging: ^9.0.0

Doctor Summary

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

Solution

  • if you send notification from firebase console and try to print
    print(event.data); this will throw an exception because data will be null in this case you have to call event.title or body