Search code examples
firebaseflutternotificationsgoogle-cloud-functionspayload

How Should I access the data elements of the notification payload in flutter?


Below is the notification payload in cloud function for FCM notification in flutter application, I am not able figure out how to access the elements of the data:{} when the notification is received in flutter application

PAYLOAD

const payload = {
                    notification: {
                      title: `NOTIFICATION2 `,
                      body: contentMessage,
                      badge: '1',
                      sound: 'default'
                    },
                    data: {
                             click_action: 'FLUTTER_NOTIFICATION_CLICK',
                             notification2: notificationid2,
                             detail: detail,
                             senderAvatarURL: messageRecieverSenderAvatar,
                             category: 'default'
                           }
                  }

NOTIFICATION CODE

firebaseMessaging.configure(onMessage: (Map<String, dynamic> message) {

      print('onMessage: $message');
      Platform.isAndroid ? showNotification(message['notification']) : showNotification(message['aps']['alert']);
   
      return;
    }, onResume: (Map<String, dynamic> message) {
      print('onResume: $message');
      
      return;
    }, onLaunch: (Map<String, dynamic> message) {
      print('onLaunch: $message');
     
      return;
    });

Solution

  • you can use the below code to access data :

     if (message.containsKey('data')) {
        // Handle data message
        final dynamic data = message['data'];
     }
    

    once you got the data map, you can parse it.

    the package https://pub.dev/packages/firebase_messaging shows an example of handling data messages, check part with title

    1. Define a TOP-LEVEL or STATIC function to handle background messages