On this page13 sections
Lecture 008: Background Messages
| Category | 2: Push Notifications |
| Lecture | 008 of 014 |
| Estimated video length | 12 min |
| Target | Flutter 3.44 · Dart 3.12 · FlutterFire (latest) |
| Level | Intermediate |
When a message arrives and the app isn't on screen, the system shows the notification: but your code can run too, before any tap. That needs a special top-level function.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Practice Questions · Answers · Takeaways · Full Code
Prerequisites
Lecture 006: the three app states.
Learning Objectives
- Know when a background handler runs
- Write it as a top-level function with
@pragma('vm:entry-point') - Register it with
onBackgroundMessagebeforerunApp - Know what you can and can't do inside it
1. What a Background Handler Is For
When the app is in the background or closed, the system shows the notification itself. A background handler additionally lets your code react the moment the message arrives (save it, update a badge count, sync data) without waiting for a tap.
2. Writing It
@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
print('Background message: ${message.messageId}');
}Three rules:
| Rule | Why |
|---|---|
Top-level: outside every class (a static method also works) | the system starts it in a separate Dart isolate, with no widgets and no objects from your app |
@pragma('vm:entry-point') | stops the release build from removing the function as "unused" |
Firebase.initializeApp() inside | the separate isolate hasn't initialized Firebase yet |
3. Registering It
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
runApp(const MyApp());
}Register it before runApp, once.
4. Inside the Handler
- ✅ Save to local storage (Hive, shared_preferences), call an API, log.
- ❌ Show dialogs, navigate, use
navigatorKeyorsetState: there's no UI in that isolate. - ⏱ Finish quickly: the system may stop long work (on Android after about 20 seconds).
Code Examples
Example 1: The Full main.dart
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.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);
print('Background: ${message.data}');
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
runApp(const MyApp());
}Minimize the app, send a message with custom data, and watch the debug console: Background: {noti_type: ...} prints before you tap anything.
Common Beginner Mistakes
1. Handler inside a class as an instance method: the app crashes on registration or the handler never runs. Make it top-level.
2. Missing @pragma('vm:entry-point'): works in debug, never runs in release.
3. Wrapping initializeApp in an empty try { } catch (e) {}: it hides the real error.
If initialization fails, you want to see why.
4. Showing UI from the handler: there is no app UI in that isolate.
Best Practices
- Keep the handler short: store, then let the app react when it opens.
- Pass the same
optionsas inmain. - Test background behaviour in a release build too (
flutter run --release).
Practice Questions
- Why must the background handler be top-level?
- What does
@pragma('vm:entry-point')do? - Where do you call
onBackgroundMessage? - Can the handler show a dialog?
Practice Answers
- It runs in a separate isolate with no access to your app's objects or widgets.
- Keeps the function from being stripped from release builds.
- In
main, afterFirebase.initializeAppand beforerunApp. - No: there is no UI in that isolate.
Key Takeaways
- Background handlers run when a message arrives with the app not on screen.
- Top-level,
@pragma('vm:entry-point'),Firebase.initializeApp()inside. - Register with
FirebaseMessaging.onBackgroundMessagebeforerunApp. - No UI; keep the work short.
Full Code (Copy-Paste Reference)
Everything the app needs up to and including this lecture, file by file.
firebase_notification_handling.dart, dialog_promo_code.dart and notification_status.dart
are unchanged from Lecture 007.
lib/main.dart
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'firebase_notification_handling.dart';
import 'firebase_options.dart';
// Top-level (NOT a class method) - the system runs this in its own isolate,
// with no access to your app's widgets or objects.
@pragma('vm:entry-point') // stops a release build from stripping this as "unused"
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// The separate isolate hasn't initialized Firebase yet - do it here too.
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
print('Background message: ${message.data}');
// Safe here: save to local storage, call an API, log. NOT safe: dialogs,
// navigation, setState - there is no UI in this isolate.
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
// Register once, before runApp.
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
static final navigatorKey = GlobalKey<NavigatorState>();
@override
void initState() {
super.initState();
FirebaseNotificationHandling.registerNotificationPermission();
FirebaseNotificationHandling.firebaseOnMessageNotificationHandle(navigatorKey);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey,
home: const HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Notify Demo')),
body: const Center(child: Text('Allow notifications when prompted')),
);
}
}