firebase / flutterfire

šŸ”„ A collection of Firebase plugins for Flutter apps.
https://firebase.google.com/docs/flutter/setup
BSD 3-Clause "New" or "Revised" License
8.5k stars 3.92k forks source link

firebase_messaging: firebase push notification empty notification while app is in forground #12667

Closed sonumagnus closed 2 months ago

sonumagnus commented 2 months ago

Is there an existing issue for this?

Which plugins are affected?

Messaging

Which platforms are affected?

Android

Description

I have setup firebase push notification with _firebasemessaging and _flutter_localnotification (to show notification in foreground). push notification works fine in background but in foreground it shows an empty notification along with an flutter local notification. How can we get rid of this empty notification. firebase_messaging_bug_screenshot

Reproducing the issue

This is my flutter dart code implementation for _firebasemessaging:

Future<void> handleBackgroundMessage(RemoteMessage message) async {
  print("Title: ${message.notification?.title}");
  print("Body: ${message.notification?.body}");
  print("Payload: ${message.data}");
}

void onNotificationResponse(NotificationResponse payload) {
  final message = RemoteMessage.fromMap(jsonDecode(payload.payload!));
  FirebaseApi().handleMessage(message);
}

class FirebaseApi {
  final _firebaseMessaging = FirebaseMessaging.instance;

  final _androidChannel = const AndroidNotificationChannel(
    'high_importance_channel',
    'High Importance Notifications',
    description: 'This Channel is used for important notification',
    importance: Importance.high,
  );

  final _localNotifications = FlutterLocalNotificationsPlugin();
  void handleMessage(RemoteMessage? message) {
    if (message == null) return;
    print(message.notification?.title);
  }

  Future initLocalNotifications() async {
    const android = AndroidInitializationSettings('@drawable/ic_launcher');
    const iOS = DarwinInitializationSettings();
    const setting = InitializationSettings(android: android, iOS: iOS);

    await _localNotifications.initialize(
      setting,
      onDidReceiveNotificationResponse: onNotificationResponse,
      onDidReceiveBackgroundNotificationResponse: onNotificationResponse,
    );

    final platform = _localNotifications.resolvePlatformSpecificImplementation<
        AndroidFlutterLocalNotificationsPlugin>();

    await platform?.createNotificationChannel(_androidChannel);
  }

  Future initPushNotifications() async {
    await _firebaseMessaging.setForegroundNotificationPresentationOptions(
      alert: false,
      badge: true,
      sound: true,
    );

    _firebaseMessaging.getInitialMessage().then(handleMessage);
    FirebaseMessaging.onMessageOpenedApp.listen(handleMessage);
    FirebaseMessaging.onBackgroundMessage(handleBackgroundMessage);

    FirebaseMessaging.onMessage.listen((message) async {
      final notification = message.notification;
      // final data = notification.android.imageUrl;
      message.mutableContent;

      final BigPictureStyleInformation? bigPictureStyleInformation;
      if (notification?.android?.imageUrl.isNotEmptyAndNotNull ?? false) {
        final image =
            await http.get(Uri.parse(notification?.android?.imageUrl ?? ''));
        bigPictureStyleInformation = BigPictureStyleInformation(
          ByteArrayAndroidBitmap.fromBase64String(
            base64Encode(image.bodyBytes),
          ),
        );
      } else {
        bigPictureStyleInformation = null;
      }

      if (notification == null) return;
      _localNotifications.show(
        notification.hashCode,
        notification.title,
        notification.body,
        NotificationDetails(
          android: AndroidNotificationDetails(
            _androidChannel.id,
            _androidChannel.name,
            channelDescription: _androidChannel.description,
            icon: '@drawable/ic_launcher',
            sound: const UriAndroidNotificationSound('default'),
            styleInformation: bigPictureStyleInformation,
          ),
        ),
        payload: jsonEncode(message.toMap()),
      );
    });
  }

  Future<void> initNotifications() async {
    await _firebaseMessaging.setAutoInitEnabled(true);
    await _firebaseMessaging.requestPermission();
    final fcmToken = await _firebaseMessaging.getToken();
    debugPrint('Token: $fcmToken');
    initPushNotifications();
    initLocalNotifications();
  }
}

in main.dart i have:

await FirebaseApi().initNotifications();

and in AndroidManifest.xml file:

<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="high_importance_channel" />

Firebase Core version

2.29.0

Flutter Version

3.19.5

Relevant Log Output

No response

Flutter dependencies

Expand Flutter dependencies snippet
```yaml Replace this line with the contents of your `flutter pub deps -- --style=compact`. ```

Additional context and comments

No response

TarekkMA commented 2 months ago

Hey @sonumagnus, Thank you for reporting this. I've run the firebase_messaging example app (which is configred similar to the code you've provided) and it only sends one notification.

Can you share with me how you are sending the notification?

sonumagnus commented 2 months ago

Hi @TarekkMA, Thank you for looking into this. I'm using Firebase Cloud Messaging (FCM) to send notifications. Specifically, I'm sending them through the Firebase push dashboard provided by Firebase.

I appreciate your help in troubleshooting this issue. Let me know if you need any additional details or if there's a specific way you'd like me to share more information about the notifications I'm sending.

TarekkMA commented 2 months ago

@sonumagnus, Can you please try the example app found here: (https://github.com/firebase/flutterfire/tree/master/packages/firebase_messaging/firebase_messaging/example) and try to see if this issue exists?

sonumagnus commented 2 months ago

Hi, @TarekkMA , Thank you for the suggestion to try the example app from the Firebase GitHub repository.

The example app provided by Firebase in their GitHub repository already has Firebase integrated, and I don't have access to the Firebase console or dashboard for that specific app. Since the example app is pre-configured with Firebase, it might be using a shared Firebase project or a demo project set up by Firebase.

To test push notifications with this example app, I believe I would need to re-integrate Firebase and connect it with my own Firebase account to send notifications. However, I'm not sure if modifying the Firebase configuration in the example app would affect its functionality or if it's intended for demonstration purposes only.

Could you please confirm if I should re-integrate Firebase with my account to test push notifications with this example app, or if there's another way to proceed without modifying the pre-configured Firebase setup in the example app?

I appreciate your guidance on this matter.

TarekkMA commented 2 months ago

Yes use your firebase backend to test.

sonumagnus commented 2 months ago

Hi @TarekkMA, I tested the firebase_messaging example app from the Firebase GitHub repository using my Firebase backend, and it works fine as expected. Since you've also tested my code and found it to work fine, what other factors could potentially be causing this bug?

TarekkMA commented 2 months ago

Hello @sonumagnus,

It appears that this may not be an issue with Firebase or FlutterFire. It could be possible that there is an error in how the local notifications plugin is being used?

sonumagnus commented 2 months ago

Hi @TarekkMA,

I removed the flutter_local_notifications package and its implementation completely from the app to test it out. However, even without it, the firebase_messaging still displays an empty notification in the foreground.

TarekkMA commented 2 months ago

I suggest you use firebase admin nodejs to send the notification instead of the console and try again. I will be closing this issue since it's not a bug with flutterfire

danishrafiqe commented 2 months ago

@sonumagnus @TarekkMA I have also the same issue

TarekkMA commented 2 months ago

Hey @danishrafiqe,

Could you please try testing the example app and let us know if you're still encountering this issue? If it persists with the example app, feel free to open a new issue, and we'll take a look!

danishrafiqe commented 1 month ago

@TarekkMA is their any way to stop FCM notification just receive listener from Firebase and we can show our own Notification from Any external Package

sonumagnus commented 1 month ago

Hello @TarekkMA and @danishrafiqe,

I've identified the root cause of the empty notification issue we were experiencing. It turns out that the notix_inapp_flutter package was the culprit. Upon removing it from the application, the problem was resolved.

Note:- notix_inapp_flutter is a monetization package with the capability of displaying notification ads.