Flutter FCM onBackgroundMessage handler gives null check error

1,291

It seems that you are putting FirebaseMessaging.onBackgroundMessage(notificationHandler) along with notificationHandler function within a class. However, that contradicts with the official docs of FlutterFire here. You need to fulfill these conditions for this function to work properly:

  1. It must not be an anonymous function.
  2. It must be a top-level function (e.g. not a class method which requires initialization).

My suggestion to you is that try to put the function notificationHandler that you are using as an argument outside the class that you are calling FirebaseMessaging.onBackgroundMessage() from. It worked with me.

Share:
1,291
Burak Cabadan
Author by

Burak Cabadan

I am Computer Science student. My main working area is Flutter and I am working as a Freelancer Flutter Developer.

Updated on November 27, 2022

Comments

  • Burak Cabadan
    Burak Cabadan over 1 year

    I am trying to implement notifications for my app, but when initializing notifications FirebaseMessaging.onBackgroundMessage(notificationHandler)gives error

    Error:

    E/flutter (28265): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Null check operator used on a null value E/flutter (28265): #0 MethodChannelFirebaseMessaging.registerBackgroundMessageHandler (package:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:173:53) E/flutter (28265): #1 FirebaseMessagingPlatform.onBackgroundMessage= (package:firebase_messaging_platform_interface/src/platform_interface/platform_interface_messaging.dart:108:16) E/flutter (28265): #2 FirebaseMessaging.onBackgroundMessage (package:firebase_messaging/src/messaging.dart:100:31)

    notificationHandler:

    Future<void> notificationHandler(RemoteMessage message) async {
        /// do sth with data
    }
    

    Note: FirebaseMessaging.onMessage and FirebaseMessaging.onMessageOpenedApp works without error