Minimum reproducible code:

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

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

  // Works.  
  FirebaseMessaging.onBackgroundMessage(_foo);
}

Future<void> _foo(RemoteMessage message) async {
  print(message);
}

Here's the error:

E/flutter (14716): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception:
                   Null check operator used on a null value
E/flutter (14716): #0      MethodChannelFirebaseMessaging.registerBackgroundMessageHandler 
                          (package:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:179:53)
E/flutter (14716): #1      FirebaseMessagingPlatform.onBackgroundMessage= (package:firebase_messaging_platform_interface/src/
                          platform_interface/platform_interface_messaging.dart:101:16)
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.