我将firebase_messaging 6.0.9
与flutter 1.12.13
一起使用。在仓库的自述文件中:https://pub.dev/packages/firebase_messaging#-readme-tab-表示将onBackgroudMessage
回调声明为静态或顶级方法。我做了,但是当此回调调用非静态方法时,它不起作用。以下示例通过单例类对此进行了演示:
class NotificationService {
static NotificationService _instance;
final FirebaseMessaging _firebase;
static NotificationService get instance => _instance;
NotificationService._internal() : this._firebase = FirebaseMessaging();
factory NotificationService() {
if (_instance == null) {
_instance = NotificationService._internal();
_instance._firebase.configure(
onBackgroundMessage: NotificationService.staticHandler
);
}
return _instance;
}
static Future<dynamic> staticHandler(Map<String, dynamic> msg) {
print("Static Func >>> $msg"); // Successfully prints
return NotificationService.instance.instanceFunc(msg); // Fails here, complaining that it's being invoked on null.
}
Future<dynamic> instanceFunc(Map<String, dynamic> msg) {
print("Instance Func >>> $msg");
}
void myVarFunc() {
print("This is my var func");
}
}
在main.dart
中,通知服务工厂构造函数称为:
import 'package:myProject/services/notification/notification_service.dart';
run(MyApp());
class MyApp extends StatelessWidget {
final NotificationService _ns = NotificationService();
NotificationService.instance.myVarFunc(); // Prints successfully.
.......
.......
.......
}
instanceFunc的调用失败,表示它在null上被调用。以下是日志:
I/flutter ( 6935): Static Func >>> {data: {title: Title_is_here, message: Message_is_here}}
I/flutter ( 6935): Unable to handle incoming background message.
I/flutter ( 6935): NoSuchMethodError: The method 'instanceFunc' was called on null.
I/flutter ( 6935): Receiver: null
I/flutter ( 6935): Tried calling: instanceFunc(_LinkedHashMap len:1)
我不太确定这是否是处理这种情况的正确方法。由于我是Dart和Flutter的新手,因此我的知识非常有限。我不能声明所有事物都是静态的并且可以正常工作,那不是IMO的好设计。我可能在这里错过了一些东西。
答案 0 :(得分:0)
出于某些原因,无法在onBackgroundMessage上获得回调:-
例如:-
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
printDebug("onMessage foreground: $message");
},
onBackgroundMessage: Platform.isIOS ? null : _myBackgroundMessageHandler,
onLaunch: (Map<String, dynamic> message) async {
printDebug("onLaunch Kill: $message");
},
onResume: (Map<String, dynamic> message) async {
print("onResume Background: $message");
},
);
static Future<dynamic> _myBackgroundMessageHandler(
Map<String, dynamic> message) async {
print("onBackgroundMessage: $message");
return Future<void>.value();
}
注意:-如果删除通知键,则通知未在系统通知托盘中呈现。为此,您可以本地通知。