On this page14 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. The Three App States
  4. 2. Foreground: onMessage
  5. 3. Background Tap: onMessageOpenedApp
  6. 4. Launch Tap: getInitialMessage
  7. 5. Inside a RemoteMessage
  8. Code Examples
  9. Common Beginner Mistakes
  10. Best Practices
  11. Practice Questions
  12. Practice Answers
  13. Key Takeaways
  14. Full Code (Copy-Paste Reference)

Lecture 006: Receiving Messages: Foreground, Opened & Launch

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

A notification can reach your app in three situations: while it's open, when the user taps it with the app in the background, and when the tap launches a closed app. Each has its own listener.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Practice Questions · Answers · Takeaways · Full Code


Prerequisites

Lecture 005: messaging added and permission granted.


Learning Objectives

  • Name the three app states and what the system does in each
  • Handle messages with onMessage, onMessageOpenedApp and getInitialMessage
  • Read a RemoteMessage's notification and data
  • Send a test message from the Firebase console

1. The Three App States

StateThe system shows a notification?Your code hears about it
Foreground: app open on screenAndroid: no. iOS: only with Lecture 005's presentation optionsimmediately, via onMessage
Background: app minimizedyeswhen the user taps it, via onMessageOpenedApp
Terminated: app closedyeswhen the tap launches the app, via getInitialMessage()

2. Foreground: onMessage

dart
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  print('Foreground: ${message.notification?.title}');
});

It's a stream: the function runs for every message that arrives while the app is open. Android shows nothing on its own here; you show a dialog (Lecture 007) or a local notification (with the flutter_local_notifications package).

3. Background Tap: onMessageOpenedApp

dart
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  print('Opened from background: ${message.notification?.title}');
});

4. Launch Tap: getInitialMessage

dart
final RemoteMessage? message = await FirebaseMessaging.instance.getInitialMessage();
if (message != null) {
  print('Launched by: ${message.notification?.title}');
}

Not a stream: a one-time question asked at startup: "was I opened by a notification?" It returns null for a normal launch.

5. Inside a RemoteMessage

FieldHolds
message.notification?.title / .bodythe visible text (if the message has a notification part)
message.dataa Map<String, dynamic> of your own key-value pairs
message.messageId, .sentTimeidentifiers

Code Examples

Example 1: All Three Listeners

dart
// lib/firebase_notification_handling.dart
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';

class FirebaseNotificationHandling {
  static Future<void> registerNotificationPermission() async {
    // ... Lecture 005
  }

  static void firebaseOnMessageNotificationHandle(
      GlobalKey<NavigatorState> navigatorKey) {
    // 1. App was closed and the user tapped a notification
    FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? message) {
      if (message != null) {
        notificationHandler(navigatorKey, 2, message);
      }
    });

    // 2. App was in the background and the user tapped a notification
    FirebaseMessaging.onMessageOpenedApp.listen((message) {
      notificationHandler(navigatorKey, 2, message);
    });

    // 3. App is open
    FirebaseMessaging.onMessage.listen((message) {
      notificationHandler(navigatorKey, 1, message);
    });
  }

  static Future<void> notificationHandler(GlobalKey<NavigatorState> navigatorKey,
      int delaySeconds, RemoteMessage message) async {
    print('Message: ${message.toMap()}');
    // Lecture 007 shows a dialog here
  }
}

delaySeconds gives the app time to finish building its first screen after a launch (2 s) before showing anything; in the foreground 1 s is enough. Lecture 007 uses it.

dart
// lib/main.dart
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(),
    );
  }
}

Example 2: Send a Test Message

Firebase console → Run → Messaging → Create your first campaign → Firebase Notification messages. Enter a title and text → Send test message → paste the device token (Lecture 009 prints it) → Test. Try it with the app open, minimized, and fully closed, and watch which listener prints.


Common Beginner Mistakes

1. Waiting for a banner in the foreground on Android: it doesn't appear. onMessage fires; showing something is your job.

2. Expecting onMessageOpenedApp after a cold start: a launch from closed goes to getInitialMessage() only. Handle both.

3. Testing taps with the debugger: killing the app from the IDE isn't the same as the user closing it. Test the terminated state by swiping the app away, then tapping the notification.


Best Practices

  • Register all listeners once, early (initState of the root widget).
  • Route all three into one handler function so behaviour is consistent.
  • Put the information your app needs in data; notification is just for display.

Practice Questions

  1. Which listener handles a message while the app is open?
  2. The app is closed and the user taps a notification. Which API tells you?
  3. Why is getInitialMessage not a stream?
  4. Where do your own key-value pairs arrive?

Practice Answers

  1. FirebaseMessaging.onMessage.
  2. FirebaseMessaging.instance.getInitialMessage().
  3. The app can only be launched once: it answers a single startup question.
  4. message.data.

Key Takeaways

  • Foreground → onMessage; background tap → onMessageOpenedApp; launch tap → getInitialMessage().
  • Android shows nothing in the foreground: you decide what to show.
  • RemoteMessage has notification (display) and data (your payload).
  • Send test messages from the console's Messaging page.

Full Code (Copy-Paste Reference)

Everything the app needs up to and including this lecture, file by file. notificationHandler only prints for now: Lecture 007 makes it show a real dialog.

lib/firebase_notification_handling.dart

dart
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';

class FirebaseNotificationHandling {
  static Future<void> registerNotificationPermission() async {
    final settings = await FirebaseMessaging.instance.requestPermission(
      alert: true,
      badge: true,
      sound: true,
    );
    print('Notification permission: ${settings.authorizationStatus}');

    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );
  }

  /// Wires up all three ways a message can reach the app, routing every one
  /// through the same handler so behaviour stays consistent.
  static void firebaseOnMessageNotificationHandle(
      GlobalKey<NavigatorState> navigatorKey) {
    // 1. App was closed and the user tapped a notification to launch it.
    FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? message) {
      if (message != null) {
        notificationHandler(navigatorKey, 2, message);
      }
    });

    // 2. App was in the background and the user tapped a notification.
    FirebaseMessaging.onMessageOpenedApp.listen((message) {
      notificationHandler(navigatorKey, 2, message);
    });

    // 3. App is open right now.
    FirebaseMessaging.onMessage.listen((message) {
      notificationHandler(navigatorKey, 1, message);
    });
  }

  static Future<void> notificationHandler(GlobalKey<NavigatorState> navigatorKey,
      int delaySeconds, RemoteMessage message) async {
    print('Message: ${message.toMap()}');
    // Lecture 007 replaces this print with a real dialog.
  }
}

lib/main.dart

dart
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

import 'firebase_notification_handling.dart';
import 'firebase_options.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // Gives non-widget code (the notification handler) a BuildContext to work with.
  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')),
    );
  }
}