Minimum reproducible code:

void main() {
  // All type of initialization is done. 

  // Throws null exception. 
  FirebaseMessaging.onBackgroundMessage((RemoteMessage message) async {

  // Works.  

Future<void> _foo(RemoteMessage message) async {

Here's the error:

E/flutter (14716): [ERROR:flutter/lib/ui/] Unhandled Exception:
                   Null check operator used on a null value
E/flutter (14716): #0      MethodChannelFirebaseMessaging.registerBackgroundMessageHandler 
E/flutter (14716): #1      FirebaseMessagingPlatform.onBackgroundMessage= (package:firebase_messaging_platform_interface/src/
E/flutter (14716): #2      FirebaseMessaging.onBackgroundMessage (package:firebase_messaging/src/messaging.dart:83:31)

I don't understand how come there be a null exception on using an anonymous function? Although docs states that this should not be an anonymous function but a null exception for that or am I misinterpreting something?

Solution 1: cas

the cloud messaging docs:

There are a few things to keep in mind about your background message handler:

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

Since the handler runs in its own isolate outside your applications context, it is not possible to update application state or execute any UI impacting logic. You can however perform logic such as HTTP requests, IO operations (updating local storage), communicate with other plugins etc.