E/flutter(26872):[错误:flutter/lib/ui/ui_dart_state.cc(199)] 未处理的异常:对空值使用空检查运算符 E/颤振(26872):#0
MethodChannelFirebaseMessaging.registerBackgroundMessageHandler (包:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:173:53) E/颤振(26872):#1
FirebaseMessagingPlatform.onBackgroundMessage= (包:firebase_messaging_platform_interface/src/platform_interface/platform_interface_messaging.dart:108:16)
// Background Messaging Set Up
Future<void> _firebaseMessagingBackgroundHandler(
RemoteMessage message) async {
print('background message');
}
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(....)
我在 Android 系统上遇到此代码错误。除非应用程序终止,否则一切正常。
Android 上的功能:
什么在 Android 上不起作用:
iOS 上的功能:
什么在 iOS 上不起作用:
我不知道为什么我在 Android 系统上收到空值错误以及如何解决此问题?另外,在iOS上,当应用程序终止时,我是否真的无法收到
Data only
推送通知?
我和你有同样的错误,在同一行。我查看了docs,它说了关于后台消息处理程序的两件事。
就我而言,它不是顶级函数,它是在类内部声明的。当您将处理程序移出任何类或函数,使其成为顶级函数并且不需要任何类或方法初始化时,错误就会消失。
_firebaseMessagingBackgroundHandler 函数应该位于主函数之外。
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
}
Future<void> main() async {
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(
...
);
}
就我而言,仅仅按照文档所说的去做是不够的。所以我意识到我应该在 main 函数中的所有内容之前添加
WidgetsFlutterBinding.ensureInitialized()
,如下所示:
void main() {
WidgetsFlutterBinding.ensureInitialized();
FirebaseMessaging.onBackgroundMessage(_handleMessage);
runApp(const Homino());
}
Future<void> backgroundNotification() async {
// await FirebaseMessaging.instance.setDeliveryMetricsExportToBigQuery(true);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
if (kDebugMode) {
print("message ===> $message");
print("message ===> ${message.sentTime}");
print("message ===> ${message.notification?.title}");
print("message ===> ${message.notification?.body}");
}
if (message.notification!.title!.isNotEmpty &&
message.notification!.body!.isNotEmpty) {
// Can use package:flutter_local_notifications for show notifications in app.
}
});
}