ios – Flutter FCM notification faucet doesn’t name `getInitialMessage()`

ios – Flutter FCM notification faucet doesn’t name `getInitialMessage()`


I have been engaged on a Flutter app the place it must assist having the ability to faucet a notification and it takes you someplace within the app. Nevertheless, when the notification is tapped, it would not invoke any of the callbacks that I create. It simply opens the app usually to the house web page. I ship notifications from an Node.js backend and I take advantage of the firebase-admin npm bundle to ship a notification.

I ship a notification like this:

/**
 * Set off sending a notification
 */
const sendNotification = async ({
    title,
    physique,
    information,
    notificationType,
    matter,
    sendTo,
    mediaUrl,
}) => {
    let tokens = [];
    if (sendTo) {
        console.log(`sending focused notitification to: ${sendTo}`);
        tokens = await getUserFCMTokens(sendTo);
    }
    const notification = {
        information: {
            ...information,
            notificationType: NOTIFICATION_TYPE[notificationType].toString(),
            title: title,
            physique: physique,
        },
        ...(matter && { matter: matter }),
        ...(tokens.size > 0 && { tokens }),
        apns: {
            headers: {
                'apns-priority': '5',
            },
            payload: {
                aps: {
                    contentAvailable: true,
                },
            },
        },
        android: {
            precedence: 'excessive',
            notification: {
                click_action: 'FLUTTER_NOTIFICATION_CLICK',
                precedence: 'excessive',
                sound: 'default',
            },
        },
    };

    console.log(notification);

    strive {
        if (tokens.size > 0) {
            // Ship to a number of units
            const response = await admin
                .messaging()
                .sendEachForMulticast(notification);
            console.log(
                `Efficiently despatched message to ${response.successCount} units`
            );
            if (response.failureCount > 0) {
                console.log(
                    `Didn't ship message to ${response.failureCount} units`
                );
                response.responses.forEach((resp, idx) => {
                    if (!resp.success) {
                        console.log(
                            `Didn't ship to token at index ${idx}: ${resp.error}`
                        );
                    }
                });
            }
        } else if (matter) {
            // Ship to matter
            const response = await admin.messaging().ship(notification);
            console.log('Efficiently despatched message:', response);
        } else {
            console.log('No legitimate recipients (tokens or matter) specified');
        }
    } catch (error) {
        console.error('Error sending notification:', error);
    }
};

a notification may appear like this when it’s printed out:

{
  information: {
    group: '6716a89768497667e665546c',
    media: '',
    message: '6716a8d868497667e66554a4',
    notificationType: '3',
    title: 'title goes right here',
    physique: '@zh22: Message goes right here '
  },
  matter: 'group_6716a89768497667e665546c',
  apns: { headers: { 'apns-priority': '5' }, payload: { aps: [Object] } },
  android: {
    precedence: 'excessive',
    notification: {
      click_action: 'FLUTTER_NOTIFICATION_CLICK',
      precedence: 'excessive',
      sound: 'default'
    }
  }
}

Then, inside foremost.dart on the shopper aspect, I initialize the Firebase background handler and in addition set the getInitialMessage callback to open to a sure display screen within the app when the notification is clicked.

void foremost() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(choices: DefaultFirebaseOptions.currentPlatform);

  await AppData.provoke();

  FirebaseMessaging.onMessage.hear((RemoteMessage message) {
    print("onMessage: $message");
  });

  FirebaseMessaging.onMessageOpenedApp.hear((RemoteMessage message) {
    print("onMessageOpenedApp: $message");
    NotificationHandler.handleNotificationOnTap(message);
  });

  FirebaseMessaging.onBackgroundMessage(_onBackgroundMessage);

  FirebaseMessaging.occasion
      .getInitialMessage()
      .then(NotificationHandler.handleNotificationOnTap);

  runApp(
    ShowCaseWidget(builder: (context) {
      return const MyApp();
    }),
  );
}

@pragma("vm:entry-point")
Future _onBackgroundMessage(RemoteMessage message) async {
  print("onBackgroundMessage: $message");
  print("information: ${message.information}");

  closing NotificationRepository notificationRepository =
      NotificationRepositoryImpl();

  closing FlutterLocalNotificationsPlugin localNotificationsPlugin =
      FlutterLocalNotificationsPlugin();
  // present notification
  const AndroidNotificationDetails androidNotificationDetails =
      AndroidNotificationDetails(
          "basecamp_notifications", "Basecamp Notifications",
          significance: Significance.max,
          precedence: Precedence.excessive,
          ticker: 'ticker');

  const DarwinNotificationDetails iosNotificationDetails =
      DarwinNotificationDetails(
          presentAlert: true,
          presentSound: true,
          interruptionLevel: InterruptionLevel.lively);

  int notificationId = 1;

  const NotificationDetails platformSpecifics = NotificationDetails(
      android: androidNotificationDetails, iOS: iosNotificationDetails);

  await localNotificationsPlugin.initialize(
    const InitializationSettings(
      android: AndroidInitializationSettings("@mipmap/ic_launcher"),
      iOS: DarwinInitializationSettings(),
    ),
    onDidReceiveNotificationResponse: (NotificationResponse particulars) {
  
      if (particulars.payload != null) {
        closing information = json.decode(particulars.payload!);
        closing message = RemoteMessage(information: Map.from(information));
        NotificationHandler.handleNotificationOnTap(message);
      }
    },
  );

    closing title = message.information["title"];
    closing physique = message.information["body"];

    await localNotificationsPlugin.present(
        notificationId, title, physique, platformSpecifics,
        payload: message.information.toString());
  
}

@pragma('vm:entry-point')
void notificationTapBackground(NotificationResponse notificationResponse) {
  print(notificationResponse);
  // NotificationHandler.handleNotificationOnTap();
}

I attempted setting NotificationHandler.handleNotificationTap() because the callback on each the native notification plugin’s onDidReceiveNotificationResponse attribute and in addition with FirebaseMessaging.onBackgroundHandler. Neither are being referred to as once I faucet the notification obtained on the bodily gadget.

Once I get a notification from the backend, the output on the app aspect appears like this:

flutter: onBackgroundMessage: Occasion of 'RemoteMessage'
flutter: information: {physique: @zh22: Message goes right here, message: 6716a8d868497667e66554a4, title: @title goes right here, group: 6716a89768497667e665546c, notificationType: 3, media: }
flutter: remoteMessage: null

discover that remoteMessage: null is also printed when a notification is obtained, which I believe is unusual.

Lastly, once I faucet a notification, nothing is printed, main me to imagine that getInitialMessage is being not referred to as on the proper time, andonMessageOpenedApp would not appear to be referred to as in any respect. I even have a print assertion inside NotificationHandler.handleNotificationTap() that’s by no means printed on this complete course of, main me to imagine that the perform isn’t entered.

At present working this on iOS. Made certain to incorporate the Push Notification functionality and Xcode. FirebaseAppDelegateProxyEnabled is about to NO.
Why is it that none of those callbacks are working once I faucet a notification?

Leave a Reply

Your email address will not be published. Required fields are marked *