Sub topic 3
Reacting to notification taps
This chapter covers how a tapped notification reaches your code, how to show messages while the app is open, how to route users to the right screen, and how to find out why a message never arrived. It assumes you have a working Flutter app with firebase_messaging set up, that you can read streams and async/await code, and that you have stored a registration token.
Handling a tap
A tap reaches your app through one of two streams or one future, depending on the app state:
FirebaseMessaging.onMessageOpenedAppfires when the app was in the background.FirebaseMessaging.instance.getInitialMessage()returns the message that launched a terminated app, ornull.
final navigatorKey = GlobalKey<NavigatorState>();
void handleTap(RemoteMessage message) {
final route = message.data['route'];
if (route != null) {
navigatorKey.currentState?.pushNamed(route);
}
}Pass navigatorKey to MaterialApp, and call handleTap from both entry points.
Showing foreground notifications
FCM does not display a system banner when the app is in the foreground. Use a local notifications plugin such as flutter_local_notifications to show one yourself. Pass the payload along so that a tap on the local banner can reuse handleTap.
Opening the right screen from a payload
Put routing data in the data map, because data arrives in every app state. Keep the values as strings, and validate the route before you push it.
Sending to groups with topics
Call FirebaseMessaging.instance.subscribeToTopic('news') to subscribe a device to a topic. One send to /topics/news then reaches every subscribed device.
Storing and maintaining tokens on your server
Tokens change when the app is reinstalled or the device restores data. Listen to onTokenRefresh and upload each new token to your server, and delete tokens that the server receives as unregistered.
Testing and debugging delivery
Use the Firebase console's test message option with a single token to confirm delivery. Then check the common causes of missing messages:
| Symptom | Likely cause |
|---|---|
| Nothing appears | Permission denied, or the device is offline |
| Works on Android, not iOS | APNs key or capability missing in Xcode |
| Background tap does nothing | Route key missing from `data` |
| Sends succeed but no device gets them | Stale or unregistered tokens |
Exercise
Exercise
A message carries route "/orders/42" in its data map. The app is terminated when the user taps the notification. Which call do you use to read that route, and why is it not enough to listen only to onMessageOpenedApp?
Show answer
Call getInitialMessage() during startup and read message.data['route']. onMessageOpenedApp fires only when the app was already running in the background, so it never sees a tap that launched a terminated app.