Sub topic 8
Receiving messages while the app is open
This chapter assumes you already have firebase_core and firebase_messaging set up, notification permission granted, and a registration token you can send to. You should be comfortable with Dart streams, StatefulWidget lifecycle methods, and async/await. Here you will learn how a message reaches your code when the app is visible, what the system does and does not display, and how to avoid the usual mistakes.
What "foreground" means to FCM
FCM treats the app as being in the foreground when it is running and visible to the user. In that state, messages go straight to your Dart code through one stream, FirebaseMessaging.onMessage. The operating system does not route them through the system tray first.
This matters because of a platform difference:
- Android: a message that contains a
notificationblock is not shown in the system tray while the app is in the foreground. Your code receives it and decides what to do. - iOS: the message also reaches
onMessage. The system shows a banner only if you opt in to foreground presentation.
The same stream fires for notification messages and data-only messages. Only the contents of the RemoteMessage differ.
The RemoteMessage object
Every handler receives a RemoteMessage. These fields are the ones you will use most:
| Field | Type | Notes |
|---|---|---|
| `messageId` | `String?` | Unique ID assigned by FCM. Useful for de-duplication and logs. |
| `notification` | `RemoteNotification?` | `null` for data-only messages. Holds `title` and `body`. |
| `data` | `Map<String, dynamic>` | Your custom key-value payload. Values are always strings. |
| `from` | `String?` | Sender ID, or the topic path for topic messages. |
| `sentTime` | `DateTime?` | When FCM sent the message, according to the server. |
| `collapseKey` | `String?` | Set when the sender used a collapse key. |
Never assume notification is present. A server that sends only a data block produces a message where message.notification is null, and message.notification!.title will throw.
Listening to onMessage
onMessage is a broadcast stream, so you can attach several listeners. Each call to listen returns a StreamSubscription. Keep it and cancel it when you no longer need it.
import 'dart:async';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
class MessageListener extends StatefulWidget {
const MessageListener({super.key, required this.child});
final Widget child;
@override
State<MessageListener> createState() => _MessageListenerState();
}
class _MessageListenerState extends State<MessageListener> {
StreamSubscription<RemoteMessage>? _subscription;
@override
void initState() {
super.initState();
_subscription = FirebaseMessaging.onMessage.listen(_handleMessage);
}
void _handleMessage(RemoteMessage message) {
if (!mounted) return;
final title = message.notification?.title ?? 'New message';
final body = message.notification?.body ?? message.data['summary'] ?? '';
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('$title\n$body')),
);
}
@override
void dispose() {
_subscription?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) => widget.child;
}Wrap this widget around your Scaffold or place it inside the MaterialApp.home subtree. ScaffoldMessenger.of(context) needs a MaterialApp above it, and a Scaffold below it if you want the snackbar to appear above a bottom bar.
Why the cancel matters
If you listen in initState and never cancel, the callback keeps running after the widget is gone. It will then call setState or use a dead BuildContext. The mounted check protects you from the crash, but it does not stop the leak. During development, hot restart creates a fresh isolate, but hot reload keeps old state. If you attach a listener in a place that runs more than once, such as build, you will see duplicate handling: one message triggers two snackbars.
Attach listeners once, in initState or during app startup.
Showing the system banner on iOS
On iOS, ask the system to present foreground notifications. Call this once after Firebase is initialized:
Future<void> configureForegroundPresentation() async {
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}With these options set, iOS shows its normal banner and plays the sound for any message that contains a notification block. onMessage still fires, so your code runs too. If you also show your own in-app banner, the user sees two alerts. Pick one:
- Use the system presentation and make
_handleMessageupdate state only. - Leave the options off and draw your own UI in
_handleMessage.
The method has no visible effect on Android. There, the system never presents foreground FCM messages.
Choosing what to do with a foreground message
A message arriving while the user is looking at your app calls for judgment. A banner can interrupt the user, and sometimes the right response is to change the screen. Common choices:
- In-app banner or snackbar. Cheap and consistent across platforms. It disappears when the user leaves the app, and it is not saved in the system tray.
- Local notification. Use a plugin such as
flutter_local_notificationsto post a real system notification. The user then sees the same tray entry they would see in the background. This needs an Android notification channel and extra setup, which a later chapter covers. - Silent state update. If the message means "your order status changed" and the order screen is open, refresh the data and show nothing. Data messages suit this best.
A practical pattern is to decide by message type. Put a type key in data, then switch on it:
void routeForegroundMessage(RemoteMessage message) {
final type = message.data['type'] as String?;
switch (type) {
case 'chat':
debugPrint('Add chat message to the open conversation');
case 'order_update':
debugPrint('Refresh order ${message.data['orderId']}');
default:
debugPrint('Show generic banner: ${message.notification?.title}');
}
}This uses Dart 3 switch statements, so no break is needed. Call routeForegroundMessage from _handleMessage.
Sending a message to test this
Use the FCM HTTP v1 request body below. The data map carries your routing key, and the notification block provides the title and body. Every value in data must be a string, so write "orderId": "42", not 42.
{
"message": {
"token": "DEVICE_REGISTRATION_TOKEN",
"notification": {
"title": "Order shipped",
"body": "Your order #42 is on its way."
},
"data": {
"type": "order_update",
"orderId": "42"
}
}
}Run the app in the foreground, send this, and check three things: the console shows your debugPrint output, the snackbar appears, and (on iOS with presentation enabled) the system banner appears as well.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Nothing happens on Android while the app is open | No code creates a visible alert | Show a snackbar, dialog, or local notification in `onMessage` |
| `Null check operator used on a null value` | Code uses `message.notification!` on a data-only message | Use `message.notification?.title` and read from `data` as a fallback |
| Two alerts on iOS | Both system presentation and your own banner are active | Disable one of them |
| Handler runs twice per message | Listener attached in `build` or attached twice | Attach once and cancel in `dispose` |
| `onMessage` never fires on a simulator | iOS simulators may lack APNs support, or permission is denied | Test on a physical iPhone and check `authorizationStatus` |
| `setState() called after dispose()` | Subscription not cancelled | Cancel in `dispose` and check `mounted` |
Edge cases to keep in mind
- Messages sent just before the app opens. A message that arrives a moment before the app reaches the foreground goes to the background path, not to
onMessage. Do not rely ononMessagealone to show every message. - Order is not guaranteed. FCM does not promise delivery in send order. If order matters, include a sequence number or timestamp in
dataand sort on the client. - Duplicates are possible. Use
messageIdto ignore a message you have already handled. - Handlers run on the UI isolate. Heavy work in
onMessage, such as large JSON parsing or file writes, can drop frames. Hand off long tasks asynchronously.
Exercise
A tester says your app shows a notification on iPhones while the app is open, but nothing appears on Android phones in the same situation. Both receive the message, as onMessage logs confirm. What explains the difference, and what are two ways to make Android behave similarly?
Show answer
iOS shows foreground notifications when setForegroundNotificationPresentationOptions is enabled. Android never displays FCM notification messages automatically while the app is in the foreground, so your code must create the alert. Two fixes are to show an in-app UI element such as a snackbar or dialog from the onMessage handler, or to post a local notification with a plugin such as flutter_local_notifications.
Exercise
A data-only message arrives and your onMessage handler throws a null check error on the line message.notification!.title. Rewrite the line so it falls back to a title entry in data.
Show answer
Use final title = message.notification?.title ?? message.data['title'] as String? ?? 'New message';. Data-only messages have a null notification, so the null-aware access avoids the exception and the fallback reads from the string-valued data map.