Sub topic 12
Opening the right screen from a payload
This chapter assumes you have a working FCM setup that receives messages. It also assumes you know the three entry points for incoming messages: onMessage, onMessageOpenedApp and getInitialMessage. You should also be comfortable with Flutter's Navigator and named routes.
The goal: one tap, one destination
A notification that only opens the app's home screen wastes the user's attention. A message about order 42 should open order 42. FCM does not navigate for you. It delivers a payload, and your code decides what the payload means.
The usual convention is to put a route string in the data map of the message:
{
"message": {
"token": "DEVICE_REGISTRATION_TOKEN",
"notification": {
"title": "Order shipped",
"body": "Your order #42 is on its way."
},
"data": {
"route": "/orders/42"
}
}
}Every value in data is a string. If you need an ID or a flag, encode it in the route or parse it from a string on the device.
Three entry points, one function
A tap on a notification reaches your app through different paths depending on the app state. The mistake to avoid is writing three separate navigation routines. Route all of them into a single function.
| App state when the tap happens | How your code learns about it | Timing concern |
|---|---|---|
| Terminated | `FirebaseMessaging.instance.getInitialMessage()` | The widget tree does not exist yet |
| Background | `FirebaseMessaging.onMessageOpenedApp` stream | The app is already running, so the navigator exists |
| Foreground | Not delivered by FCM. You show a local notification and use its tap callback | Depends on the plugin you use |
Navigating without a BuildContext
The message callbacks are not inside a widget's build method, so you have no BuildContext. A GlobalKey<NavigatorState> solves this. You give the key to MaterialApp, and any code can then reach the navigator through it.
import 'dart:async';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
/// Top-level path segments a notification is allowed to open.
const Set<String> allowedRoots = {'orders', 'promo'};
/// Returns a safe route string, or null if the payload should be ignored.
String? safeRoute(String? raw) {
if (raw == null) return null;
final uri = Uri.tryParse(raw);
if (uri == null || !uri.path.startsWith('/')) return null;
if (uri.pathSegments.isEmpty) return null;
if (!allowedRoots.contains(uri.pathSegments.first)) return null;
return uri.toString();
}
void openRoute(String? raw) {
final route = safeRoute(raw);
if (route == null) return;
navigatorKey.currentState?.pushNamed(route);
}
void openFromMessage(RemoteMessage message) {
openRoute(message.data['route'] as String?);
}
void main() {
runApp(const NotificationApp());
}
class NotificationApp extends StatefulWidget {
const NotificationApp({super.key});
@override
State<NotificationApp> createState() => _NotificationAppState();
}
class _NotificationAppState extends State<NotificationApp> {
StreamSubscription<RemoteMessage>? _openedSub;
@override
void initState() {
super.initState();
// Background: the app is running, so the navigator already exists.
_openedSub = FirebaseMessaging.onMessageOpenedApp.listen(openFromMessage);
// Terminated: wait until the first frame so MaterialApp has built a Navigator.
WidgetsBinding.instance.addPostFrameCallback((_) async {
final initial = await FirebaseMessaging.instance.getInitialMessage();
if (initial != null) openFromMessage(initial);
});
}
@override
void dispose() {
_openedSub?.cancel();
super.dispose();
}
Route<dynamic>? _onGenerateRoute(RouteSettings settings) {
final uri = Uri.parse(settings.name ?? '/');
if (uri.pathSegments.length == 2 && uri.pathSegments.first == 'orders') {
return MaterialPageRoute<void>(
settings: settings,
builder: (_) => OrderPage(orderId: uri.pathSegments[1]),
);
}
return MaterialPageRoute<void>(
settings: settings,
builder: (_) => const HomePage(),
);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey,
onGenerateRoute: _onGenerateRoute,
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) =>
const Scaffold(body: Center(child: Text('Home')));
}
class OrderPage extends StatelessWidget {
const OrderPage({super.key, required this.orderId});
final String orderId;
@override
Widget build(BuildContext context) =>
Scaffold(appBar: AppBar(title: Text('Order $orderId')));
}This listing leaves out Firebase initialization and the background handler. Add them to main as shown in the setup chapters.
Why wait for the first frame
getInitialMessage() can complete before MaterialApp has built its Navigator. At that moment navigatorKey.currentState is null, and the null-aware call in openRoute silently does nothing. The tap appears to work, because the app opens, but the user lands on the home screen. Deferring the call with addPostFrameCallback guarantees the navigator exists.
The initial message is consumed on read. A second call to getInitialMessage() returns null, so a tap never opens the same screen twice.
Validate the route
The data map comes from outside your app. Anyone who can send to a token or topic can set route to anything. Passing it straight to pushNamed lets a malformed or unexpected value reach screens that were never meant to be opened from a notification, such as an admin page or a screen that assumes the user is signed in.
The safeRoute function above uses an allowlist of top-level segments. Unknown values are dropped. This is cheaper than debugging a crash that only appears for one message in production.
Foreground messages and local notifications
When the app is in the foreground, FCM delivers the message to onMessage and the system does not show a banner. If you display one yourself with a local notifications plugin, the tap on that banner does not go through FCM at all. Pass the route as the local notification's payload and handle the plugin's callback with the same openRoute function.
With flutter_local_notifications, the callback is set during initialization:
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
final FlutterLocalNotificationsPlugin localNotifications =
FlutterLocalNotificationsPlugin();
Future<void> initLocalNotifications() async {
await localNotifications.initialize(
const InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
iOS: DarwinInitializationSettings(),
),
onDidReceiveNotificationResponse: (NotificationResponse response) {
openRoute(response.payload);
},
);
}When you call show in your onMessage listener, pass payload: message.data['route']. Reusing openRoute means the allowlist applies to this path too.
Edge cases
- Signed-out users. A tap can arrive before the user has logged in. Store the validated route in a variable, show the login screen, and call
openRoutewith the stored value after sign-in succeeds. - Stacking screens.
pushNamedadds to the back stack. Tapping three notifications in a row creates three order pages. If that is wrong for your app, usepushNamedAndRemoveUntilor compare with the current route name before pushing. - Missing data. A message sent from the Firebase console with no custom data has an empty
datamap.openRoute(null)returns early, and the app simply opens at its normal start screen. - Data-only messages in the background. A data-only message shows no banner, so there is nothing to tap. If you want a tap, the message needs a
notificationblock, or your background handler must create a local notification. - Declarative routers. With a router such as
go_router, callrouter.go(route)on a router instance you can reach from a top-level variable. The same three entry points and the same validation apply.
Testing the flow
Test each state separately, because each uses a different code path:
- Terminated: swipe the app away, send the message, and tap the banner. Confirm you land on the order page, not home.
- Background: press the home button, send, and tap.
- Foreground: keep the app open, send, and tap the local notification.
- Invalid: send
"route": "/admin"and confirm nothing opens.
Exercise
A tap on a notification launches your terminated app, but the user lands on the home screen instead of the order page. Your code calls getInitialMessage() in main() before runApp and passes the route to navigatorKey.currentState?.pushNamed. What is the likely cause, and how do you fix it?
Show answer
The navigator does not exist yet when the call runs, so navigatorKey.currentState is null and the null-aware call does nothing. Move the getInitialMessage() call into a widget's initState using WidgetsBinding.instance.addPostFrameCallback, so it runs after the first frame, when MaterialApp has built its Navigator.
Exercise
Why should openRoute check the route value against an allowlist before navigating, and where in the app should that check live?
Show answer
The data payload comes from outside the app, so its value can be missing, malformed or point to a screen that should not be opened from a notification. Checking it against an allowlist of permitted top-level segments prevents that. The check belongs inside the single openRoute function, so that taps from getInitialMessage, onMessageOpenedApp and the local notification callback are all validated the same way.