Flutter FCM onMessage doesn't work when listen to it

3,758

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

Share:
3,758
Andrew Maher
Author by

Andrew Maher

Updated on December 28, 2022

Comments

  • Andrew Maher
    Andrew Maher over 1 year

    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
    
    • Mol0ko
      Mol0ko about 3 years
      Hi! You try to handle incoming message in foreground, not in background, right?
    • Andrew Maher
      Andrew Maher about 3 years
      In either cases, even onMessageOpenedApp, nothing get printed
    • ALEXANDER LOZANO
      ALEXANDER LOZANO about 3 years
      i have the same problem with version ^9.1.3, i need to manage notification click event, but onforeground tap message does not work. on arrived msg a i get this in the console: "Accessing hidden method Landroid/os/WorkSource;->add(I)Z (greylist,test-api, reflection, allowed)" , and FirebaseMessaging.onMessage.listen is not triggered, my onmessage function only have a print(¨msg¨)