Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter unable to call callBack function for firebase cloud messing

I have got this error when I try to add callback function onBackgroundMessage for Flutter firebase cloud messaging.

flutter: The following ArgumentError was thrown building HomeScreen(dirty): flutter: Invalid argument(s): Failed to setup background message handler! onBackgroundMessage flutter: should be a TOP-LEVEL OR STATIC FUNCTION and should NOT be tied to a flutter: class or an anonymous function. flutter: flutter: The relevant error-causing widget was: flutter: HomeScreen flutter: file:///Users/sournvisal/Documents/projects/flutter-project/one_sala/lib/router.dart:17:39

Please help. Thanks.

like image 780
Vexal Avatar asked Dec 28 '19 03:12

Vexal


1 Answers

As the error said the onBackgroundMessage needs to be TOP-LEVEL OR STATIC FUNCTION

TOP-LEVEL function is a function that is outside a class. example:

 Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) {
   if (message.containsKey('data')) {
     // Handle data message
     final dynamic data = message['data'];
   }

   if (message.containsKey('notification')) {
     // Handle notification message
     final dynamic notification = message['notification'];
   }

   // Or do other work.
 }

STATIC FUNCTION is a function inside a class but prefixed with static keyword and do not operate on an instance, and thus do not have access to this. example:

class Fcm {
  static Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) {
    if (message.containsKey('data')) {
     // Handle data message
     final dynamic data = message['data'];
   }

   if (message.containsKey('notification')) {
     // Handle notification message
     final dynamic notification = message['notification'];
   }

   // Or do other work.
  }
}
like image 82
humazed Avatar answered Oct 19 '22 16:10

humazed