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.
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.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With