channel.invokeMethod() does not work in FirebaseMessaging.onBackgroundMessage();

87 Views Asked by At

In Flutter Calling a native method like this _channel.invokeMethod() in a

FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

gives exception

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: MissingPluginException(No implementation found for method wakeupscreen on channel flutter_native)

here is my _firebaseMessagingBackgroundHandler()

@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  print("Handling a background message: ${message.messageId}");
  await Firebase
      .initializeApp(); //make sure firebase is initialized before using it (showCallkitIncoming)

  wakeupscreen();

}

// wakeupscreen() func -- this is a global function so does not require any class instance to run

wakeupscreen() async {
  try {
    const platform = MethodChannel('flutter_native');
    await platform.invokeMethod('wakeupscreen');
  } on PlatformException catch (e) {
    print("Failed to invoke the method: '${e.message}'.");
  }
}

I tried using this same wakeupscreen() function in a normal code :

InkWell(
                  onTap: () {
                    Future.delayed(Duration(seconds: 5), () {
                      wakeupscreen();
                    });
                  },
                  child: Text("wakeup in 5 sec"),
                ),

And it works perfectly as expected when calling it normally, but as soon as the same function is called in _firebaseMessagingBackgroundHandler it throws exception.

1

There are 1 best solutions below

6
On

In main.dart, set up a method channel to handle messages from the background isolate:

// Inside main.dart

MethodChannel _channel = MethodChannel('flutter_native');

// Set up method channel to communicate with background isolate
_channel.setMethodCallHandler((call) async {
  if (call.method == 'wakeupscreen') {
    wakeupscreen(); // Call your wakeupscreen function here
  }
});

Remove method channel initialization from the wakeupscreen function:

// Remove this line from the wakeupscreen function
const platform = MethodChannel('flutter_native');

These changes ensure that the method channel is appropriately configured to manage messages from the background isolate and that the wakeupscreen function is invoked as required.