当我尝试为Flutter firebase云消息传递添加回调函数onBackgroundMessage
时遇到此错误。
flutter:构建HomeScreen(dirty)时引发了以下ArgumentError:
颤振:无效的参数:无法设置后台消息处理程序! onBackgroundMessage
颤动:应该是最高级或静态功能,不应与
flutter:类或匿名函数。
扑:
扑:相关的引起错误的小部件是:
颤动:主屏幕
颤抖:file:///Users/sournvisal/Documents/projects/flutter-project/one_sala/lib/router.dart:17:39
请帮助。 谢谢。
答案 0 :(得分:1)
错误提示onBackgroundMessage
必须为 TOP-LEVEL 或 STATIC FUNCTION
TOP-LEVEL函数是类之外的函数。例如:
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 是类内部的函数,但前缀为static
关键字,不能在实例上操作,因此无法访问this
。
例如:
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.
}
}