Flutter Firebase FCM FLUTTER_NOTIFICATION_CLICK redirect to different route with context

Viewed 24

Below code to send push notification and handling the notification click.

Everything works fine, Can able to receive message when app is running in foreground, background and terminated.

class PushNotificationService {
  
  Future<void> setupInteractedMessage() async {
    await Firebase.initializeApp();
    final StorageRepository _storageRepository = StorageRepository();

    FirebaseMessaging.instance.getToken().then((token) async {
      await _storageRepository.setNotificationToken(token!);
    });

    await enableIOSNotifications();
    await registerNotificationListeners();

   // some other functionalities...


      flutterLocalNotificationsPlugin.initialize(initSetttings, onSelectNotification: (String? payload) async {
      if (payload != null && payload.isNotEmpty) {
        Map messageMap = jsonDecode(payload);
        Navigator.pushNamed(context, '/chat', arguments: ChatArguments(messageMap.ID));
      }
    });

  }

I am calling the above class in main.dart file as below..


void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

 // above class get called for notification.
 await PushNotificationService().setupInteractedMessage();

 runApp(MyApp());

}


My issue is when user clicking on the message, get redirected to different route. I don't know how to get the context. I tried declaring globalkey and use it in context but still no luck.

Is it possible to send the context as a parameter to PushNotificationService class and use it as a context for navigation etc.

Since the function is called before the void main, can't able to send the context as a parameter

Please help me, am struggling with this.

Many thanks in advance.

0 Answers
Related