Sub topic 2
Notification messages vs data messages
This chapter assumes you know Dart async/await and streams, that your Flutter project already builds with firebase_core and firebase_messaging added, and that you can open the Firebase console.
Two message types
FCM (Firebase Cloud Messaging) sends two payload kinds. A notification message has a notification block with a title and body. The operating system shows it in the tray when the app is in the background or terminated. A data message has only a data map of string key-value pairs. Your code must handle it.
| App state | Notification message | Data message |
|---|---|---|
| Foreground | Passed to `onMessage`; no tray entry | Passed to `onMessage` |
| Background | Shown in tray by the system | Passed to background handler (Android) |
| Terminated | Shown in tray by the system | Passed to background handler (Android) |
Data values must be strings. Sending a number or a nested object fails.
Sending your first message
Send a request to the HTTP v1 endpoint. The body below combines a notification with a route in data.
{
"message": {
"token": "DEVICE_REGISTRATION_TOKEN",
"notification": {
"title": "Order shipped",
"body": "Your order #42 is on its way."
},
"data": {
"route": "/orders/42"
}
}
}curl -X POST \
"https://fcm.googleapis.com/v1/projects/PROJECT_ID/messages:send" \
-H "Authorization: Bearer ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d @message.jsonReceiving messages while the app is open
The onMessage stream delivers foreground messages. The system does not show a tray notification in this state, so you decide what to display.
void listenForForegroundMessages() {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
debugPrint('Title: ${message.notification?.title}');
debugPrint('Route: ${message.data['route']}');
});
}Receiving messages in the background and when terminated
Register a top-level handler before runApp. The @pragma('vm:entry-point') annotation keeps the function from being removed in release builds.
@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
debugPrint('Background message: ${message.messageId}');
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
runApp(const MaterialApp(home: Scaffold(body: Center(child: Text('FCM demo')))));
}Common error: a notification message sent without data shows a tray entry, but tapping it gives your app no route to open.
Exercise
A data-only message arrives on Android while the app is terminated. Which function receives it?
Show answer
The top-level function passed to FirebaseMessaging.onBackgroundMessage.