Sub topic 10
Reacting to notification taps
This chapter covers what happens when a user taps a notification, and how to capture that tap in each app state. It assumes you can already receive messages (foreground and background) and that you know basic Dart streams and async/await. Navigation from the payload is covered in a later chapter, so here we only capture the tap and read its data.
Why taps need three entry points
A tap does not always arrive the same way. It depends on the state the app was in when the notification appeared.
| App state when tapped | What the user sees | How your code learns about it |
|---|---|---|
| Foreground | No system notification (by default) | Nothing to tap. You show your own UI, covered in the local notifications chapter. |
| Background | App returns to the front | `FirebaseMessaging.onMessageOpenedApp` emits the `RemoteMessage`. |
| Terminated | App launches from scratch | `FirebaseMessaging.instance.getInitialMessage()` returns the `RemoteMessage`. |
Only messages that the operating system displayed can be tapped. That means notification messages (those with a notification block) in the background or terminated state. A data-only message produces no system notification, so there is nothing for the user to tap.
Tap while the app is in the background
onMessageOpenedApp is a broadcast stream. Subscribe once, early, and keep the subscription for the life of the app.
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
void listenForTaps() {
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
debugPrint('Tapped from background: ${message.messageId}');
debugPrint('Route: ${message.data['route']}');
});
}The stream emits only when the user taps a notification while the app process is alive in the background. It does not emit for ordinary messages and does not emit on launch from terminated.
Tap that launches the app
When the app was terminated, the tap starts a new process. The stream above is not listening yet, so the message is stored and you retrieve it with getInitialMessage().
Future<void> checkInitialMessage() async {
final message = await FirebaseMessaging.instance.getInitialMessage();
if (message != null) {
debugPrint('Launched from notification: ${message.data['route']}');
}
}Two properties matter here:
- It returns
nullwhen the app was launched normally, for example from the home screen icon. - On Android, the message is consumed after you read it. Calling it again later returns
null, so read it once and keep the result.
Wiring both into one handler
Treat both paths as the same event. A single function keeps the behavior consistent and gives you one place to add navigation later.
import 'dart:async';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
class NotificationTapHandler {
StreamSubscription<RemoteMessage>? _subscription;
Future<void> init() async {
// Terminated state: read the launching message once.
final initial = await FirebaseMessaging.instance.getInitialMessage();
if (initial != null) {
_handleTap(initial);
}
// Background state: listen for later taps.
_subscription = FirebaseMessaging.onMessageOpenedApp.listen(_handleTap);
}
void _handleTap(RemoteMessage message) {
final route = message.data['route'] as String?;
debugPrint('Notification tapped, route: $route');
// Navigation is added in the next chapters.
}
void dispose() {
_subscription?.cancel();
}
}Call init() once, after Firebase.initializeApp, from a place that lives as long as the app, such as main or the root widget's initState.
class App extends StatefulWidget {
const App({super.key});
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
final _tapHandler = NotificationTapHandler();
@override
void initState() {
super.initState();
_tapHandler.init();
}
@override
void dispose() {
_tapHandler.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(body: Center(child: Text('Tap demo'))),
);
}
}The class above needs import 'package:flutter/material.dart'; at the top of its file.
What the message contains
A RemoteMessage gives you the fields that matter for a tap.
| Field | Meaning |
|---|---|
| `messageId` | Identifier assigned by FCM. Useful for logging and de-duplication. |
| `notification` | Title and body, if the message had a `notification` block. |
| `data` | The custom key-value map. All values are strings. |
| `sentTime` | When the message was sent. |
| `from` | The sender ID or topic. |
Your routing information belongs in data. A request that carries it looks like this:
{
"message": {
"token": "DEVICE_REGISTRATION_TOKEN",
"notification": {
"title": "Order shipped",
"body": "Your order #42 is on its way."
},
"data": {
"route": "/orders/42"
}
}
}Because data values are always strings, a numeric ID arrives as "42". Parse it yourself and handle the case where the key is missing.
int? readOrderId(RemoteMessage message) {
final raw = message.data['orderId'];
if (raw == null) return null;
return int.tryParse(raw.toString());
}Edge cases and common errors
The tap does nothing on a data-only message
If you send only data, the system does not show a notification in the background, so no tap can happen. If you want a tappable notification, include a notification block, or show one yourself with a local notifications plugin from your background handler.
The initial message arrives before the UI is ready
getInitialMessage() can return while the widget tree is still building. If you navigate immediately, the navigator may not exist yet. Store the message and act on it after the first frame, for example with WidgetsBinding.instance.addPostFrameCallback. The navigation chapter builds on this.
Taps on foreground notifications
By default, a notification that arrives while the app is open is not shown by the system on Android, and on iOS it is hidden unless you enable foreground presentation. If you show one with setForegroundNotificationPresentationOptions on iOS, a tap on it is reported through onMessageOpenedApp. On Android, a notification you draw yourself with a local notifications plugin reports its tap through that plugin's callback, not through FCM.
Duplicate handling
If your app is restarted from a notification, getInitialMessage() can return the same message on a later cold start in some configurations. Compare messageId against the last handled ID that you stored, and skip repeats.
String? _lastHandledId;
void handleOnce(RemoteMessage message) {
final id = message.messageId;
if (id != null && id == _lastHandledId) return;
_lastHandledId = id;
debugPrint('Handling ${message.data}');
}Subscribing too late
If you subscribe to onMessageOpenedApp only on a screen that is not on the stack when the tap happens, you miss the event. Subscribe at the app root.
iOS requires a real device
Tap behavior depends on APNs delivery. The iOS simulator does not receive remote notifications from FCM in most setups, so verify taps on a physical iPhone.
Testing the three paths
Use the Firebase console, or send a request with a notification block and a data block, then follow these steps for each state.
- Background: open the app, press Home, send the message, tap the notification. Check that
onMessageOpenedApplogs the route. - Terminated: swipe the app away from the app switcher, send the message, tap the notification. Check that
getInitialMessagelogs the route. - Launch normally: start the app from its icon. Check that
getInitialMessagereturnsnull.
On Android, "Force stop" in system settings is different from swiping the app away. A force-stopped app receives no messages until the user opens it again, so do not use it to test the terminated state.
Summary of the working model
- A tap is reported only for notifications that the operating system displayed.
- Background taps arrive on the
onMessageOpenedAppstream. - Taps that launch the app arrive through
getInitialMessage(), which you call once at startup. - Route information lives in the string-valued
datamap. - Handle both entry points with one function, subscribe at the app root, and be ready for the UI not to exist yet.
Exercise
A user swipes your app away, receives a notification message with data: {"route": "/orders/42"}, and taps it. Your code only subscribes to FirebaseMessaging.onMessageOpenedApp in initState of the root widget, and the route is never logged. Which API do you need to add, and why does the stream not fire?
Show answer
Add a call to FirebaseMessaging.instance.getInitialMessage() at startup. When the app is terminated, the tap launches a new process, and onMessageOpenedApp only emits for taps while the app is alive in the background. The launching message is stored and returned by getInitialMessage(), which returns null on a normal launch.
Exercise
You send a message that contains only a data block while the app is in the background. The user sees no notification, so no tap is possible. Name two ways to make a tappable notification appear.
Show answer
Add a notification block (title and body) to the message so the system displays it, or show a notification yourself from the background handler using a local notifications plugin.