skip to Main Content

I’m trying to initialize Firebase messaging onBackgroundMessage and I’m getting a very unusual error I’ve tried every approach I know and can find the error still persists.

Future<void> handleBackgroundMessage(RemoteMessage message) async {
final notification = message.notification;

if (notification != null) {
  print("title: ${notification.title}");
  print("body: ${notification.body}");
} else {
  print("No notification data found in the message.");
}

final data = message.data;

print("payload: $data");
}

This is where I’m calling the handleBackgroundMessage

Future<void> initNotification() async {
try {
  await _firebaseMessaging.requestPermission();

  final fcmToken = await _firebaseMessaging.getToken();
  await _firebaseMessaging.subscribeToTopic("Church");

  print(fcmToken);

  FirebaseMessaging.onBackgroundMessage(handleBackgroundMessage);
} catch (e) {
  print("Error initializing notifications: $e");
}
}

This is where I initialized firebase in the main function

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  await FirebaseApi().initNotification();

  runApp(const MainApp());
}

this is the error I’m getting

Restarted application in 7,630ms.
W/kiibati.kiibat( 2363): Accessing hidden method Ldalvik/system/CloseGuard;->close()V (greylist,core-platform-api, linking, allowed)
W/kiibati.kiibat( 2363): Accessing hidden method Ldalvik/system/CloseGuard;->warnIfOpen()V (greylist,core-platform-api, linking, allowed)
I/flutter ( 2363): c14bRHbiQtmVpfJ5RlOpng:APA91bFm5XYVPU4CvICaNb8oFkYWw80T7ZK1RehffDPgna59WxX1nWRzEFSltY7mH4cBRrpmb07ZMZNKY0g3TrlbnclGG8oqn8XGL8oL8SzhOCUR8r1dCpW1H6qBzxVztj4mJi3p7Sne
E/flutter ( 2363): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value
E/flutter ( 2363): #0      MethodChannelFirebaseMessaging.registerBackgroundMessageHandler
method_channel_messaging.dart:181
E/flutter ( 2363): #1      FirebaseMessagingPlatform.onBackgroundMessage=
platform_interface_messaging.dart:102
E/flutter ( 2363): #2      FirebaseMessaging.onBackgroundMessage
messaging.dart:73
E/flutter ( 2363): #3      FirebaseApi.initNotification
firebaseapi.dart:17
E/flutter ( 2363): <asynchronous suspension>
E/flutter ( 2363): #4      main
main.dart:23
E/flutter ( 2363): <asynchronous suspension>
E/flutter ( 2363):
D/SharedPreferencesImpl( 2363): Time required to fsync /data/user/0/com.kiibati.kiibati/shared_prefs/com.google.android.gms.appid.xml: [<1: 0, <2: 0, <4: 0, <8: 1, <16: 2, <32: 0, <64: 0, <128: 0, <256: 0, <512: 1, <1024: 0, <2048: 0, <4096: 0, <8192: 0, <16384: 0, >=16384: 0]
W/DynamiteModule( 2363): Local module descriptor class for com.google.android.gms.providerinstaller.dynamite not found.
I/DynamiteModule( 2363): Considering local module com.google.android.gms.providerinstaller.dynamite:0 and remote module com.google.android.gms.providerinstaller.dynamite:0
W/ProviderInstaller( 2363): Failed to load providerinstaller module: No acceptable module com.google.android.gms.providerinstaller.dynamite found. Local version is 0 and remote version is 0.
D/FLTFireMsgReceiver( 2363): broadcast received for message
W/FLTFireMsgService( 2363): A background message could not be handled in Dart as no onBackgroundMessage handler has been registered.
W/FirebaseMessaging( 2363): Unable to log event: analytics library is missing
W/FirebaseMessaging( 2363): Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.

2

Answers


  1. The error "Unhandled Exception: Null check operator used on a null value" indicates that you are trying to use a null check operator on a variable that is null. In this case, it seems the issue occurs when you are trying to register the background message handler using FirebaseMessaging.onBackgroundMessage(handleBackgroundMessage).

    To resolve this issue, you should ensure that handleBackgroundMessage is indeed defined and not null. Also, make sure that the import and initialization of FirebaseMessaging are correctly configured. Here are some steps to follow:

    Make sure you have imported FirebaseMessaging correctly in your Dart file:

    import 'package:firebase_messaging/firebase_messaging.dart';
    

    Ensure you have initialized FirebaseMessaging in your main or at an entry point of your app:

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp();
      runApp(MyApp());
    }
    

    Verify that the handleBackgroundMessage function is defined correctly and doesn’t have any errors:

    Future<void> handleBackgroundMessage(RemoteMessage message) async {
      final notification = message.notification;
    
      if (notification != null) {
        print("title: ${notification.title}");
        print("body: ${notification.body}");
      } else {
        print("No notification data found in the message.");
      }
    
      final data = message.data;
    
      print("payload: $data");
    }
    

    Ensure that the initNotification function is called appropriately. Check for any issues with the sequence of function calls and make sure Firebase is configured correctly.Hope this helps you solve the problem.

    If the issue persists after following these steps, you may want to check the version of Firebase Messaging you are using to ensure it is up-to-date and compatible with the version of Flutter you are using.

    Login or Signup to reply.
  2. Ok please revert you code to this:

    //in your main
    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await Firebase.initializeApp(
        options: DefaultFirebaseOptions.currentPlatform,
      );
    
     FirebaseMessaging.onBackgroundMessage(handleBackgroundMessage);
    }
    
    //your handleBackgroundMessage let it just do this
    Future<void> handleBackgroundMessage(RemoteMessage message) async {
      await Firebase.initializeApp();
    }
    
    //Handle all your print statements in the `initState`
    ...
    initSate(){
     super.initState();
    
    ///Listen to foreground notification
        FirebaseMessaging.onMessage.listen((RemoteMessage message) {
          RemoteNotification? notification = message.notification;
          AndroidNotification? android = message.notification?.android;
          if (notification != null && android != null) {
            flutterLocalNotificationsPlugin.show(
              notification.hashCode,
              notification.title,
              notification.body,
              NotificationDetails(
                android: AndroidNotificationDetails(
                  channel.id,
                  channel.name,
                  channelDescription: channel.description,
                  //color: Colors.blue,
                  icon: "@drawable/ic_notification",
                ),
              ),
    
            );
    
          }
        });
        
        
        ///Background but not terminated
        FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
    
          RemoteNotification? notification = message.notification;
          AndroidNotification? android = message.notification?.android;
          ///promotion notification
          if (notification != null && android != null && message.data['type'] =='Promotion' || message.data['type'] =='promotion') {
             //navigate somewhere or print
          }
          else {
            //navigate somewhere
          }
        });
    }
    ...
    
    //You do not need this anymore
    Future<void> initNotification() async {
    try {
      await _firebaseMessaging.requestPermission();
    
      final fcmToken = await _firebaseMessaging.getToken();
      await _firebaseMessaging.subscribeToTopic("Church");
    
      print(fcmToken);
    
      FirebaseMessaging.onBackgroundMessage(handleBackgroundMessage);
    } catch (e) {
      print("Error initializing notifications: $e");
    }
    }
    

    This is from my code please replace all your variables to your liking

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search