How to access context from fcm static method flutter

Viewed 477

I have implemented FCM on my flutter app. However in my static method indeed to access context because I want to load a dialog on my home page from the background handler method. Is there a way to get this.

My Background Service handler method refuses to accept a context method for a my psh notification service class which am initialising inside my homescreen.dart file.

Future<dynamic> _myBackgroundMessageHandler
    (Map<String, dynamic> message) async {
  print("onBackground Message called");
  print(message);
  return PushNotificationService().showNotification(message);
//I need to access context from here and pass it to my showNotification method but I can't
}


class PushNotificationService{
  BuildContext buildContext;
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
 
    _firebaseMessaging.configure(
     
    onBackgroundMessage: Platform.isIOS ? null:_myBackgroundMessageHandler,

     
    );
    ///fetch user messaging token here
    getToken();
  }


  void fetchRideInfo(orderId, context, String type) {
    print("fetching info");
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) =>
          CustomProgressDialog(status:'Fetching details',),);
  

      Provider.of<MainBloc>(context, listen: false).
      fetchRideInfo(context, orderId).then((value){
        Navigator.pop(context);
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) =>
              RideRequestPage(orderId: orderId)),
        );
      }).catchError((error) {
        Navigator.pop(context);
        AlertManager.showToast(error.toString());
      });

  }

  Future showNotification(Map<String, dynamic> message) async {
    var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
      'channel id',
      'channel name',
      'channel desc',
      importance: Importance.max,
      priority: Priority.high,
      playSound: true,
      icon: "ic_stat_ic_notification",
      largeIcon: DrawableResourceAndroidBitmap("ic_launcher"),
      sound: RawResourceAndroidNotificationSound("alert")
    );

    var platformChannelSpecifics =
    new NotificationDetails(android: androidPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(
      0,
      'New Incoming Request',
      'New incoming ride request',
      platformChannelSpecifics,
      payload: 'Default_Sound',
    );
    fetchRideInfo(message['data']['orderId'], buildContext, "onBackgroundMessage");//this method don't get called cos build context is null
  }





}
1 Answers

you can use navigator key

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

and put this key in MaterialApp

                      MaterialApp(
                      navigatorKey: navigatorKey,
                      title: 'title',
                      home: SplashScreen());
                  
                

and use this navigator key from anywhere and in _myBackgroundMessageHandler

  Future<dynamic> _myBackgroundMessageHandler
      (Map<String, dynamic> message) async {
    print("onBackground Message called");
    print(message);
    return PushNotificationService().showNotification(
        message, navigatorKey.currentContext);
  }
Related