Notification show twice on flutter

545

FCM payload


{
    "to":"_some_fcm_token_",
    //remove this
    "notification": {
        "title": "this is title",
        "body": "this is subtitle"
    },
    "type": "post_like",
    "data": {
        "model":{"id":"dsaflkdskfklgdkgjdksakdk"},
        "body": "this is subtitle",
        "title": "this is title",
        "click_action": "FLUTTER_NOTIFICATION_CLICK"
    },
    "priority": "normal"
}

The first one is manually created (locally), and the other one is automatic by Firebase.

When sending a message to your device, make sure it is a notification rather than data. The documentation mentions that if you send data it will likely be ignored as a push notification. Only use it to send packets of data to the app instead.

Share:
545
Yeremia Yeri
Author by

Yeremia Yeri

Updated on January 03, 2023

Comments

  • Yeremia Yeri
    Yeremia Yeri over 1 year

    I'm stuck. My notification in the background show twice. But in the foreground only one notification. This is my code

    Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
      // If you're going to use other Firebase services in the background, such as Firestore,
      // make sure you call `initializeApp` before using other Firebase services.
      await Firebase.initializeApp();
      if(
          !AwesomeStringUtils.isNullOrEmpty(message.notification?.title, considerWhiteSpaceAsEmpty: true) ||
          !AwesomeStringUtils.isNullOrEmpty(message.notification?.body, considerWhiteSpaceAsEmpty: true)
        ){
          // print('message also contained a notification: ${message.notification.body}');
          
          String imageUrl;
          imageUrl ??= message.notification.android?.imageUrl;
          imageUrl ??= message.notification.apple?.imageUrl;
          print(imageUrl);
          if(imageUrl == null){
            var id = Random().nextInt(2147483647);
            await AwesomeNotifications().createNotification(
              content: NotificationContent(
                id: id,
                title: message.notification.title,
                body: message.notification.body,
                color: Colors.orange,
                customSound: 'resource://raw/alert',
                notificationLayout: NotificationLayout.BigText,
                channelKey: 'basic_channel_background',
                payload: {'data':message.data['payload']}
              ),
              actionButtons: [
                NotificationActionButton(
                  label: 'Lihat Selengkapnya',
                  enabled: true,
                  buttonType: ActionButtonType.Default,
                  key: 'background',
                )
              ]
            );
          }else{
            await AwesomeNotifications().createNotification(
              content: NotificationContent(
                id: Random().nextInt(2147483647),
                title: message.notification.title,
                body: message.notification.body,
                bigPicture: imageUrl,
                color: Colors.orange,
                customSound: 'resource://raw/alert',
                notificationLayout: NotificationLayout.BigPicture,
                channelKey: 'basic_channel_background',
                payload: {'data':message.data['payload']}
              ),
              actionButtons: [
                NotificationActionButton(
                  label: 'Lihat Selengkapnya',
                  enabled: true,
                  buttonType: ActionButtonType.Default,
                  key: 'background',
                )
              ]
            );
          }
        }
    }
    // End Background Message
    

    and this is my foreground code

    // Foreground Apps
    Future<void> main() async{
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
      if (!kIsWeb) {
        await FirebaseMessaging.instance
            .setForegroundNotificationPresentationOptions(
          alert: true,
          badge: true,
          sound: true,
        );
        await AwesomeNotifications().initialize(
        'resource://mipmap/launcher_icon',
        [
          NotificationChannel(
              channelGroupKey: 'basic_tests',
              channelKey: 'basic_channel',
              channelName: 'My Cahaya Notification',
              channelDescription: 'Notification channel for basic tests',
              icon: 'resource://mipmap/launcher_icon',
              importance: NotificationImportance.High,
              playSound: true,
              soundSource: 'resource://raw/alert'
          ),
           NotificationChannel(
              channelGroupKey: 'basic_background',
              channelKey: 'basic_channel_background',
              channelName: 'My Cahaya Notification Background',
              channelDescription: 'Notification channel for basic tests',
              icon: 'resource://mipmap/launcher_icon',
              importance: NotificationImportance.High,
              playSound: true,
              soundSource: 'resource://raw/alert'
          ),
        ], debug: true);
        AwesomeNotifications().actionStream.listen((event) async{
          print('event received!');
          var data = event.toMap();
          if(data['buttonKeyPressed'] == "background"){
            SharedPreferences prefs = await SharedPreferences.getInstance();
            prefs.setString("Navigate", data['payload']['data']);
          }else{
            _navigateToItemForeground(data['payload']['data']);  
          }
          // do something based on event...
          // AwesomeNotifications().actionSink.close();
        });
      } 
      
       FirebaseMessaging.onMessage.listen((RemoteMessage message) async{
          RemoteNotification notification = message.notification;
          AndroidNotification android = message.notification?.android;
          if (notification != null && android != null && !kIsWeb) {
            if(!AwesomeStringUtils.isNullOrEmpty(message.notification?.title, considerWhiteSpaceAsEmpty: true) ||
            !AwesomeStringUtils.isNullOrEmpty(message.notification?.body, considerWhiteSpaceAsEmpty: true)){
            print("something");
    
            String imageUrl;
            imageUrl ??= notification.android?.imageUrl;
            imageUrl ??= notification.apple?.imageUrl;
            
            if(imageUrl == null){
              await AwesomeNotifications().createNotification(
                content: NotificationContent(
                  id: Random().nextInt(2147483647),
                  title: notification.title,
                  body: notification.body,
                  color: Colors.orange,
                  customSound: 'resource://raw/alert',
                  notificationLayout: NotificationLayout.BigText,
                  channelKey: 'basic_channel',
                  payload: {'data':message.data['payload']}
                ),
                actionButtons: [
                  NotificationActionButton(
                    label: 'Lihat Selengkapnya',
                    enabled: true,
                    buttonType: ActionButtonType.Default,
                    key: 'test',
                  )
                ]
              );
            }else{
              await AwesomeNotifications().createNotification(
                content: NotificationContent(
                  id: Random().nextInt(2147483647),
                  title: notification.title,
                  body: notification.body,
                  bigPicture: imageUrl,
                  color: Colors.orange,
                  customSound: 'resource://raw/alert',
                  notificationLayout: NotificationLayout.BigPicture,
                  channelKey: 'basic_channel',
                  payload: {'data':message.data['payload']}
                ),
                actionButtons: [
                  NotificationActionButton(
                    label: 'Lihat Selengkapnya',
                    enabled: true,
                    buttonType: ActionButtonType.Default,
                    key: 'test',
                  )
                ]
              );
            }
          }
        }
      });
      runApp(MyApp());
    }
    // End Foreground Apps
    

    and this is my screenshot screenshot

    I've tried changing the awesome notification but the result is the same. Could you help me to solve that? I hope you can help me. Thank you very much

  • Yeremia Yeri
    Yeremia Yeri over 2 years
    0 i've send notification not data. But my phone receive two notification while my apps not opened. When my apps opened i try send notification to my phone, My phone receive one notification
  • Sahil Hariyani
    Sahil Hariyani over 2 years
    I see data in your code. payload: {'data':message.data['payload']}
  • Yeremia Yeri
    Yeremia Yeri over 2 years
    why with my payload? may i should remove that?
  • Sahil Hariyani
    Sahil Hariyani over 2 years
    yes, when you use message.data firebase automatically sends a push notification.
  • Yeremia Yeri
    Yeremia Yeri over 2 years
    i've remove that, the result is same. My notification show twice when my apps is closed. What should i do now?
  • Sahil Hariyani
    Sahil Hariyani over 2 years
    Oh sorry! my bad. Keep message.data as it is, but don't send message.notification. . When you send notification field empty, firebase will not send push notification.
  • Yeremia Yeri
    Yeremia Yeri over 2 years
    where code location "message.notification.empty" in my code?, so i can remove it
  • Sahil Hariyani
    Sahil Hariyani over 2 years
    'message.notification' is from the payload which your are sending from a backend server or from the firebase console. Just don't send notification field and it will not show the notification twice.
  • Yeremia Yeri
    Yeremia Yeri over 2 years
    if i don't send notification field, how can my apps receive notification when not opened?
  • Sahil Hariyani
    Sahil Hariyani over 2 years
    The notification field is mainly used to show title and subtitle of notification, you can put that in data field, If you send the notification field, the automatic firebase notification will pop up with the local awesome notification you are creating. I faced the same problem and this was the only doable solution I found.
  • Yeremia Yeri
    Yeremia Yeri over 2 years
    what can i put in data field?. Can you give me an example?. I've tried to not filled notification field. But the result, my notification not showing anything