On this page13 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. What a Background Handler Is For
  4. 2. Writing It
  5. 3. Registering It
  6. 4. Inside the Handler
  7. Code Examples
  8. Common Beginner Mistakes
  9. Best Practices
  10. Practice Questions
  11. Practice Answers
  12. Key Takeaways
  13. Full Code (Copy-Paste Reference)

Lecture 008: Background Messages

Category2: Push Notifications
Lecture008 of 014
Estimated video length12 min
TargetFlutter 3.44 · Dart 3.12 · FlutterFire (latest)
LevelIntermediate

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 onBackgroundMessage before runApp
  • 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

dart
@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  print('Background message: ${message.messageId}');
}

Three rules:

RuleWhy
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() insidethe separate isolate hasn't initialized Firebase yet

3. Registering It

dart
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 navigatorKey or setState: 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

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 options as in main.
  • Test background behaviour in a release build too (flutter run --release).

Practice Questions

  1. Why must the background handler be top-level?
  2. What does @pragma('vm:entry-point') do?
  3. Where do you call onBackgroundMessage?
  4. Can the handler show a dialog?

Practice Answers

  1. It runs in a separate isolate with no access to your app's objects or widgets.
  2. Keeps the function from being stripped from release builds.
  3. In main, after Firebase.initializeApp and before runApp.
  4. 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.onBackgroundMessage before runApp.
  • 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

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')),
    );
  }
}