Home > Back-end >  flutter firebase messaging handling clicked notification on background
flutter firebase messaging handling clicked notification on background

Time:01-29

I'm using the firebase_messaging package on my flutter app and it works perfectly for everything except that when the app on the background and I get a notification it only opens the app and never do what I ask it does after opening the app ..here is my code:

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.
  await Firebase.initializeApp();

  print("Handling a background message: ${message.messageId}");
  final dynamic data = message.data;
  print("data is $data");
  if(data.containsKey('request_id')) {
    print("we are inside ..!");
    RegExp exp = RegExp(r'\d ');
    var id = int.parse(exp.firstMatch(data['request_id']!)!.group(0)!);
    OpenRequestsController openRequestsController = Get.isRegistered<OpenRequestsController>()?Get.find():Get.put(OpenRequestsController());
    OpenRequest matchingRequest = openRequestsController.openRequestsList.firstWhere((request) => request.id == id);
    print("the request from the list is $matchingRequest");
    openRequestsController.openRequestDetails(matchingRequest,false);

  }
}

what happens here is that it tries to run the whole function when the message is received not when clicked .. and ofc it fails because the app is not already running in the foreground

CodePudding user response:

For opening the application and moving to the said screen you need to implement onMessageOpenedApp in the initstate of your first stateful widget which will let the application to know that it is supposed to open the application when a notification being clicked. The code function should look like this:

FirebaseMessaging.onMessageOpenedApp.listen((message) {
  Get.to(() => const MainScreen()); // add logic here
});

It is better if you could assign identifiers for the type of screens you want to open on clicking a particular notification while sending the notification and implement an if-else or switch statement here on the basis of message type.

Thanks

  • Related