Fcm background Notification in Flutter

Viewed 5443

I have implemented a notification in the backgound with firebase messaging. But, the problem is this; how can I return the data from the function myBackgroundMessageHandler to FirebaseNotification?

Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) {
      return Future<void>.value();
    }

    class FirebaseNotifications {
      FirebaseMessaging _firebaseMessaging;
      FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

      void setUpFirebase() {
        _firebaseMessaging = FirebaseMessaging();
      }

      void fcmListeners() {
        _firebaseMessaging.configure(
          onMessage: (Map<String, dynamic> message) async {
            print("OnMessage");
            processNotification(message);
            return;
          },
          onBackgroundMessage: myBackgroundMessageHandler,
          onLaunch: (Map<String, dynamic> message) async {
            print("onLaunch");
            processNotification(message);
            return;
          },
          onResume: (Map<String, dynamic> message) async {
            print("onResume");
            processNotification(message);
            return;
          },
        );
      }

      processNotification(message) {}
    }
3 Answers

I write a little program, which can permit to listen a background message push notification when your application is on background or terminated (tested on Android only because I haven't iOS account).

This is the link to the repository Click here!

You have to use the sharedPreference to save any data coming from the notification and access it within the app. As the function is running on it's own isolate, it won't be able to access any static or global variable within the app. Here's a demo:

Future<void> firebaseMessagingBackgroundHandler(
  RemoteMessage remoteMessage,
    ) async {
      String logicFlow = remoteMessage.data['logic_flow'];
      if (logicFlow != null) {
      if (logicFlow.isNotEmpty) {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('required_string', logicFlow);
    }
  }
}

After this: You can access the string from anywhere within your app using the same key that you used to store .i.e.

final prefs = await SharedPreferences.getInstance();
String requiredString  = await prefs.getString('required_string');

  
Related