Flutter: access SharedPreferences from onBackgroundMessage method of FirebaseMessaging

Viewed 368

In my Flutter app I want to save data received from a Firebase Data Message to SharedPreferences. I have the FirebaseMessaging object configured like this:

_firebaseMessaging.configure(
        onMessage: (Map<String, dynamic> message) {
          // this works fine
          print("onMessage: ");
        },
        onLaunch: (Map<String, dynamic> data) {
          print("onLaunch: ");
        },
        onResume: (Map<String, dynamic> data) {
          print("onResume: ");
        },
        onBackgroundMessage: myBackgroundMessageHandler,
      );

And this is the top-level myBackgroundMessageHandler method:

Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) {
    // This doesn't work
    print("background message"); // this isn't even printed!
    SharedPreferences.getInstance().then(...) // here I have to save some data
  }

The problem is that myBackgroundMessageHandler seems not to be called at all. However, the notification is received on the phone. I also tryed to remove the notification field from the message and in that case myBackgroundMessageHandler is called but the notification doesn't arrive. Is there a way to both receive the notification and trigger the method?

0 Answers
Related