When I click on the notification on background, it doesn’t redirect to the page I want.
I checked, and navigatorkey.currentContext is null.
(I’m using go_router, get_it, provider)
I referred to the blog below.
https://zzingonglog.tistory.com/40
https://zzingonglog.tistory.com/41
final navigatorKey = GlobalKey<NavigatorState>();
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
String payloadData = jsonEncode(message.data);
print('Got a message in background');
if (message.notification != null) {
PushNotification.showSimpleNotification(
title: message.notification!.title!,
body: message.notification!.body!,
payload: payloadData,
);
}
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
await PushNotification.init();
await PushNotification.localNotiInit();
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
String payloadData = jsonEncode(message.data);
print('Got a message in foreground');
if (message.notification != null) {
PushNotification.showSimpleNotification(
title: message.notification!.title!,
body: message.notification!.body!,
payload: payloadData,
);
}
});
final NotificationAppLaunchDetails? notificationAppLaunchDetails =
await flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails();
if (notificationAppLaunchDetails?.didNotificationLaunchApp ?? false) {
String payload =
notificationAppLaunchDetails!.notificationResponse?.payload ?? "";
print('Got a message in terminated');
Future.delayed(Duration(seconds: 1), () {
navigatorKey.currentContext
?.push('/notification/message', extra: payload);
});
}
diSetup();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: router,
title: 'MyApp',
theme: ThemeData(
scaffoldBackgroundColor: Colors.white,
appBarTheme: AppBarTheme(
// backgroundColor: ColorStyles.primary40,
titleTextStyle: TextStyles.extraLargeTextBold.copyWith(
color: ColorStyles.black,
),
backgroundColor: Colors.transparent,
),
useMaterial3: true,
),
);
}
}
I tried defining Globalkey here and there.
2
Answers
The reason it isn’t navigating to the correct screen/page once clicking a notification, Is, since you have to actually assign the key to the
MaterialApp
.Essentially, you need to ‘tie’ the key to the
MaterialApp
to let it know what key to use.In your code:
Assign the navigatorKey to both GoRouter and MaterialApp.router
First, define a global navigatorKey and assign it to both your GoRouter and MaterialApp.router.
Then, in your MyApp widget:
Use router.go() Instead of navigatorKey.currentContext?.push()
In your notification handler, rather than using navigatorKey.currentContext?.push(), you should use the GoRouter instance to navigate. Since you might not have a BuildContext, using the router directly is more reliable.
First, make sure your GoRouter instance is accessible where you need it. You can achieve this by defining it globally or using a service locator.
Handle Initial Routes When the App Is Terminated
When your app is launched from a terminated state due to a notification tap, you should handle the initial route appropriately.
In your main() function:
Then, modify your MyApp widget to accept the initial route:
Access Payload in the Target Screen
In your route definition for ‘/notification/message’, make sure to handle the extra data:
Summary
Why This Works
By following these steps, your app should correctly navigate to the desired page when a notification is tapped, regardless of whether the app is in the foreground, background, or terminated.