If you work with firebase messaging and wanna get background message, you may get this error. I got this error as I was working in my video chatting app.
FlutterFire Messaging: An error occurred in your background messaging handler:
I/flutter (16581): You are trying to use contextless navigation without
I/flutter (16581): a GetMaterialApp or Get.key.
I/flutter (16581): If you are testing your app, you can use:
I/flutter (16581): [Get.testMode = true], or if you are running your app on
I/flutter (16581): a physical device or emulator, you must exchange your [MaterialApp]
I/flutter (16581): for a [GetMaterialApp].
At first glance it may look like a Getx error, but it’s not.
The entry point of this error is
FirebaseMessaging.onBackgroundMessage(
FirebaseMessagingHandler.firebaseMessagingBackground
);
FirebaseMessaging.oBackgroundMessage is the function that takes a handler. Our handler is FirebaseMessagingHandler.firebaseMessagingBackground. This handler is supposed to wake up the app if background messages arrive.
In the background handler you are supposed to do background work. You must not do any kind of UI work or navigation. You must not do anything with context.
If you work with context you may get this error.
@pragma('vm:entry-point')
static Future<void> firebaseMessagingBackground(RemoteMessage message) async {
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform,);
print("message data: ${message.data}");
print("message data: ${message}");
print("message data: ${message.notification}");
if(message!=null){
if(message.data!=null && message.data["call_type"]!=null) {
if(message.data["call_type"]=="cancel"){
FirebaseMessagingHandler.flutterLocalNotificationsPlugin.cancelAll();
// await setCallVocieOrVideo(false);
var _prefs = await SharedPreferences.getInstance();
await _prefs.setString("CallVocieOrVideo", "");
}
if(message.data["call_type"]=="voice" || message.data["call_type"]=="video"){
var data = {
"to_token":message.data["token"],
"to_name":message.data["name"],
"to_avatar":message.data["avatar"],
"doc_id":message.data["doc_id"]??"",
"call_type":message.data["call_type"],
"expire_time":DateTime.now().toString(),
};
print(data);
var _prefs = await SharedPreferences.getInstance();
await _prefs.setString("CallVocieOrVideo", jsonEncode(data));
Get.to(AppRoutes.INITIAL);
}
}
You see the last line, I called a route to navigate to other screen. That line caused the issues. Because going to a new route requires context. It does not work with context.
Get.to(AppRoutes.INITIAL);
Remove that and error is gone.
Resolved, thanks for post.
Most welcome
Most welcome