Sub topic 8
Receiving Messages While the App Is Open
Prerequisites and the foreground model
This chapter assumes that you have a Flutter project connected to Firebase, have added firebase_core and firebase_messaging, and understand Dart async/await, streams, and StatefulWidget lifecycle methods.
A foreground message is a message received while the app is visible on screen. Firebase Cloud Messaging (FCM) delivers it to the FirebaseMessaging.onMessage stream. Your app decides what to do with it.
Listening with `onMessage`
Register the listener after Firebase has been initialized. Store the stream subscription and cancel it when the widget is removed. This prevents callbacks from reaching a widget that no longer exists.
import 'dart:async';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const MaterialApp(home: MessagePage()));
}
class MessagePage extends StatefulWidget {
const MessagePage({super.key});
@override
State<MessagePage> createState() => _MessagePageState();
}
class _MessagePageState extends State<MessagePage> {
StreamSubscription<RemoteMessage>? _messageSubscription;
String _status = 'Waiting for a foreground message';
@override
void initState() {
super.initState();
_messageSubscription =
FirebaseMessaging.onMessage.listen(_handleMessage);
}
void _handleMessage(RemoteMessage message) {
final title = message.notification?.title ?? 'Data message';
final body = message.notification?.body ?? message.data.toString();
if (!mounted) return;
setState(() {
_status = '$title\n$body';
});
}
@override
void dispose() {
_messageSubscription?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Foreground messages')),
body: Center(child: Text(_status, textAlign: TextAlign.center)),
);
}
}RemoteMessage.notification contains display fields such as title and body. RemoteMessage.data contains your application-specific key-value pairs. Treat data values as strings when creating FCM requests, then parse them in the app if necessary.
| Message content | What `onMessage` receives | Typical foreground action |
|---|---|---|
| Notification payload | `message.notification` | Update the UI or show a local notification |
| Data payload | `message.data` | Perform application logic or navigate after user action |
| Both payloads | Both properties | Use notification text and data together |
Foreground display behavior
A notification payload does not always create a system notification when the app is visible. The foreground callback runs, but the operating system may leave display decisions to your app. To show a banner or sound, add a local notifications plugin and create a notification inside _handleMessage.
On iOS, foreground presentation settings can also allow alerts, badges, and sounds. Configure those settings deliberately because they affect the user experience.
Common errors include registering the listener before Firebase.initializeApp, forgetting to cancel subscriptions, assuming message.notification is always present, and expecting foreground messages to appear automatically in the notification tray.
Exercise
A foreground message contains only data: {"route": "/orders/42"}. Which property should the listener read, and why might message.notification be null?
Show answer
Read message.data['route']. The message has no notification payload, so FCM has no title or body to place in message.notification.