2

I am trying to implement notifications for my app, but when initializing notifications FirebaseMessaging.onBackgroundMessage((message) => myBackgroundMessageHandler(message))gives the following error. I have looked through this issue and this issue and have taken the function myBackgroundMessageHandler that I'm using as an argument outside the class but the error still persists.

Below is the error:

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):

Below is my code:

Future<dynamic> myBackgroundMessageHandler(RemoteMessage message) {
  print('backgroundMessage: message => ${message.toString()}');

}


void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage((message) => myBackgroundMessageHandler(message));

  }

scott lee
  • 546
  • 5
  • 23

1 Answers1

2

You might want to try and write your main function the following way. It might be that you need to initialize Firebase if you want to run your function in the background.

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());
}

If you would like to see my implementation of Firebase Messaging with Flutter, check my github repo.

pythonNovice
  • 1,130
  • 1
  • 14
  • 36
  • Thank you. Yes, it worked. Do you happen to know why it didn't work for my code though? It seems almost the same – scott lee Aug 18 '21 at 01:57