3

I try to push a new route when user opens a notification but I get the following error:

FlutterFire Messaging: An error occurred in your background messaging handler:
You are trying to use contextless navigation without
a GetMaterialApp or Get.key.
If you are testing your app, you can use:
[Get.testMode = true], or if you are running your app on
a physical device or emulator, you must exchange your [MaterialApp]      
for a [GetMaterialApp].

This is how I implemented my notifcations:

main.dart
 
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  await setupFlutterNotifications();
  showFlutterNotification(message);
  Get.toNamed(message.data['view']); // I get the error in this line
  print('Handling a background message ${message.data}');
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  if (!kIsWeb) {
    await setupFlutterNotifications();
  }
  runApp(
    GetMaterialApp(
      title: 'e-Rădăuți',
      debugShowCheckedModeBanner: false,
      builder: EasyLoading.init(),
      getPages: AppPages.routes,
      initialRoute:
          await IsFirstRun.isFirstRun() ? Routes.ONBOARD : Routes.HOME,
      initialBinding: AppBindings(),
      navigatorObservers: [
        AnalyticsController().getAnalyticsObserver(),
      ],
      theme: ThemeData(
        scaffoldBackgroundColor: Color(0xFFFFFFFF),
        primaryColor: Color(0xFFFFFFFF),
      ),
      navigatorKey: Get.key,
    ),
  );
}

If I try to push a new screen (not from notifications) it works like expected.

Any idea on what I've done wrong? I've added navigatorKey and I have replaced [MaterialApp] with [GetMaterialApp]

t3nsa
  • 680
  • 6
  • 21
  • `_firebaseMessagingBackgroundHandler` will be called if a message is received while your app is in the background. You won't be able the access navigation from here, you options are limited, [check here](https://firebase.google.com/docs/cloud-messaging/flutter/receive#background_messages). You can use `FirebaseMessaging.onMessageOpenedApp`, which will be called if the user clicks on your notification. – Peter Koltai Aug 25 '22 at 19:46
  • 1
    @PeterKoltai thx, I implemented that function already but it does nothing if the app is killed, I've found a solution to fix this problem – t3nsa Aug 28 '22 at 20:57
  • @t3nsa can you please post your solution? – Shajeel Afzal Nov 25 '22 at 00:02
  • @ShajeelAfzal I've solved this by getting the data in the message and redirecting the user in my home page ( in the initState() ) – t3nsa Dec 09 '22 at 14:41

0 Answers0