Sub topic 9
Receiving Messages in the Background and When Terminated
Assume you already know Dart async/await, Flutter app lifecycle basics, and have configured firebase_core and firebase_messaging for Android and iOS. This chapter focuses on code that runs when the app is not visible.
Background message handling
A background message arrives while the app is minimized or another app is visible. Firebase Messaging runs a background handler in a separate Dart isolate. An isolate is an independent Dart execution context, so the handler cannot use widget state, a BuildContext, or your normal navigation stack.
The handler must be a top-level function. It must not be nested inside a class or another function. The @pragma('vm:entry-point') annotation prevents release-mode tree shaking from removing it.
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(
RemoteMessage message,
) async {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
debugPrint('Background message: ${message.messageId}');
debugPrint('Data: ${message.data}');
}
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')),
),
),
);
}Keep background work short. You can update a local database, process data, or schedule local work. Do not try to display a Flutter widget from this handler.
Notification messages and data messages
A notification message contains a notification payload. When the app is in the background, Android or iOS usually displays it in the system notification tray. Your Dart background handler might not receive the notification portion. If the message also contains data, that data is normally available when the user taps the notification.
A data-only message contains only data. Its background delivery depends on platform rules, message priority, battery-saving settings, and APNs configuration. iOS may delay or omit background execution, and a user-forced-quit app generally cannot be woken for background processing.
The delivery path can be summarized as follows:
Handling a terminated app
A terminated app is not running when the user taps its notification. Check getInitialMessage() during startup:
Future<void> checkInitialMessage() async {
final message = await FirebaseMessaging.instance.getInitialMessage();
if (message == null) {
return;
}
final route = message.data['route'];
debugPrint('App launched by notification: $route');
// Navigate after your app's navigator is ready.
}If the app was already running in the background, use FirebaseMessaging.onMessageOpenedApp. Both callbacks should pass validated payload data to one navigation function. Never trust a route or identifier from a notification without checking that it is supported.
Exercise
Why must a background handler be top-level, and which API checks whether a notification launched a terminated app?
Show answer
The handler runs in a separate isolate and cannot depend on widget state, so it must be top-level. FirebaseMessaging.instance.getInitialMessage() checks the terminated launch case.