Sub topic 12
Opening the right screen from a payload
Assume you know basic Flutter navigation, asynchronous Dart, and the FCM setup from the previous chapters. This chapter focuses on routing after a user taps a notification. The same notification can reach your app through different entry points depending on its state.
A message payload should contain a small, stable route description. For example:
{
"route": "/orders",
"orderId": "42"
}The route value selects a screen. The orderId value tells that screen which order to load.
Choose the correct message entry point
Use both listeners. onMessageOpenedApp handles a tap when the app is in the background. getInitialMessage handles a tap that launches the app from a terminated state.
| App state after the tap | FCM entry point |
|---|---|
| Background | `onMessageOpenedApp` |
| Terminated | `getInitialMessage()` |
| Foreground | Your foreground message handler |
The foreground handler does not automatically represent a notification tap. If you display a local notification while the app is open, configure that plugin to pass its payload to the same routing function.
Validate before navigating
Treat notification data as untrusted input. A server mistake or an old notification might contain a route your app no longer supports. Allow only known routes, and do not pass arbitrary route strings to navigation.
The following coordinator handles both tap paths. It also waits if navigation is not ready when the initial message arrives.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
final navigatorKey = GlobalKey<NavigatorState>();
RemoteMessage? pendingMessage;
const allowedRoutes = {'/orders', '/inbox'};
void openFromMessage(RemoteMessage message) {
final route = message.data['route'];
if (route is! String || !allowedRoutes.contains(route)) {
debugPrint('Ignoring unsupported notification route: $route');
return;
}
final navigator = navigatorKey.currentState;
if (navigator == null) {
pendingMessage = message;
return;
}
navigator.pushNamed(route, arguments: message.data);
}
class App extends StatefulWidget {
const App({super.key});
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
@override
void initState() {
super.initState();
FirebaseMessaging.onMessageOpenedApp.listen(openFromMessage);
FirebaseMessaging.instance.getInitialMessage().then((message) {
if (message != null) openFromMessage(message);
});
WidgetsBinding.instance.addPostFrameCallback((_) {
final message = pendingMessage;
pendingMessage = null;
if (message != null) openFromMessage(message);
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey,
home: const Scaffold(body: Center(child: Text('Home'))),
onGenerateRoute: (settings) {
switch (settings.name) {
case '/orders':
final data = settings.arguments! as Map<String, dynamic>;
return MaterialPageRoute(
builder: (_) => Text('Order ${data['orderId']}'),
);
case '/inbox':
return MaterialPageRoute(
builder: (_) => const Text('Inbox'),
);
default:
return null;
}
},
);
}
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const App());
}Avoid common navigation errors
- Register
onMessageOpenedAppduring app startup, before the user can tap a notification. - Always call
getInitialMessage; the stream does not replay a terminated-state launch. - Keep payload values as strings when sending through FCM.
- Validate required fields such as
orderIdbefore loading data. - Prefer
pushNamedfor a detail screen so the Back button returns to the previous screen. - Decide what should happen when a user taps an expired notification. Showing a safe fallback screen is better than throwing an exception.
Exercise
Which API handles a notification tap that launches an app from a terminated state?
Show answer
FirebaseMessaging.instance.getInitialMessage().