我正在尝试为我的应用程序实现通知,但在初始化通知时 FirebaseMessaging.onBackgroundMessage((message) => myBackgroundMessageHandler(message)) 给出以下错误。我浏览过this issue和 this issue并采用了我在类外部用作参数的函数 myBackgroundMessageHandler,但错误仍然存在。
下面是错误:
E/flutter (10115): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value E/flutter (10115): #0
MethodChannelFirebaseMessaging.registerBackgroundMessageHandler (package:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:179:53) E/flutter (10115): #1
FirebaseMessagingPlatform.onBackgroundMessage= (package:firebase_messaging_platform_interface/src/platform_interface/platform_interface_messaging.dart:101:16) E/flutter (10115): #2 FirebaseMessaging.onBackgroundMessage (package:firebase_messaging/src/messaging.dart:83:31) E/flutter (10115): #3 main (package:okepos/main.dart:130:21) E/flutter (10115):
下面是我的代码:
Future<dynamic> myBackgroundMessageHandler(RemoteMessage message) {
print('backgroundMessage: message => ${message.toString()}');
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage((message) => myBackgroundMessageHandler(message));
}
最佳答案
您可能想尝试按以下方式编写主函数。如果您想在后台运行函数,您可能需要初始化 Firebase。
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp();
print('Handling a background message ${message.messageId}');
if (message.notification != null) {
print(message.notification.title);
print(message.notification.body);
}
// Create a notification for this
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// Background Message Handler
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(MyApp());
}
如果您想查看我使用 Flutter 实现的 Firebase Messaging,请查看 my github repo .
关于firebase - 未处理的异常 : Null check operator used on a null value (Flutter FCM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68820605/