Sub topic 10
Reacting to Notification Taps
Assume you know basic Flutter navigation, Dart async/await, streams, and the Firebase Messaging setup from earlier chapters. This chapter focuses on deciding which screen to open when a user taps a notification.
A notification tap can enter your app in two ways:
onMessageOpenedAppruns when the app was in the background.getInitialMessage()returns the message when the tap launched the app from a terminated state.
A foreground message does not create a system notification automatically. If you display a local notification while the app is open, that plugin has its own tap callback. Handle that callback with the same routing function.
Use one routing function
Keep notification parsing and navigation in one function. This prevents the background and terminated paths from behaving differently. Treat values from message.data as untrusted input. Allow only routes that your application understands.
The following example uses a global navigatorKey, so the messaging callbacks can navigate without a BuildContext.
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>();
void openFromMessage(RemoteMessage message) {
final route = message.data['route'];
const allowedRoutes = {'/orders', '/profile'};
if (route is! String || !allowedRoutes.contains(route)) {
return;
}
navigatorKey.currentState?.pushNamed(
route,
arguments: message.data,
);
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
FirebaseMessaging.onMessageOpenedApp.listen(openFromMessage);
runApp(
MaterialApp(
navigatorKey: navigatorKey,
routes: {
'/': (_) => const HomePage(),
'/orders': (_) => const Text('Orders'),
'/profile': (_) => const Text('Profile'),
},
),
);
WidgetsBinding.instance.addPostFrameCallback((_) async {
final message =
await FirebaseMessaging.instance.getInitialMessage();
if (message != null) {
openFromMessage(message);
}
});
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return const Scaffold(
body: Center(child: Text('Home')),
);
}
}pushNamed adds the destination to the navigation stack. If tapping a notification should replace the current screen, use pushReplacementNamed. If repeated taps should not create duplicate pages, check the current route or use a routing package that supports replacement and deep links.
Match the payload to the destination
The server might send a route and an identifier:
{
"message": {
"token": "DEVICE_REGISTRATION_TOKEN",
"notification": {
"title": "Order shipped",
"body": "Your order #42 is on its way."
},
"data": {
"route": "/orders",
"orderId": "42"
}
}
}The orders screen can read orderId from the route arguments and load the latest data from your server. Do not trust the payload as proof that the user can view an order. Enforce authorization when the app requests the order.
Exercise
Which callback should handle a notification tap when the app was terminated, and why should the route value be validated?
Show answer
Call getInitialMessage(), because the tap launched the app. Validate the route to prevent malformed or unsupported payload data from navigating the app unexpectedly.