On this page14 sections
- Prerequisites
- Learning Objectives
- 1. The Three App States
- 2. Foreground: onMessage
- 3. Background Tap: onMessageOpenedApp
- 4. Launch Tap: getInitialMessage
- 5. Inside a RemoteMessage
- Code Examples
- Common Beginner Mistakes
- Best Practices
- Practice Questions
- Practice Answers
- Key Takeaways
- Full Code (Copy-Paste Reference)
Lecture 006: Receiving Messages: Foreground, Opened & Launch
| Category | 2: Push Notifications |
| Lecture | 006 of 014 |
| Estimated video length | 16 min |
| Target | Flutter 3.44 · Dart 3.12 · FlutterFire (latest) |
| Level | Intermediate |
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,onMessageOpenedAppandgetInitialMessage - Read a
RemoteMessage's notification and data - Send a test message from the Firebase console
1. The Three App States
| State | The system shows a notification? | Your code hears about it |
|---|---|---|
| Foreground: app open on screen | Android: no. iOS: only with Lecture 005's presentation options | immediately, via onMessage |
| Background: app minimized | yes | when the user taps it, via onMessageOpenedApp |
| Terminated: app closed | yes | when the tap launches the app, via getInitialMessage() |
2. Foreground: onMessage
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
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print('Opened from background: ${message.notification?.title}');
});4. Launch Tap: getInitialMessage
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
| Field | Holds |
|---|---|
message.notification?.title / .body | the visible text (if the message has a notification part) |
message.data | a Map<String, dynamic> of your own key-value pairs |
message.messageId, .sentTime | identifiers |
Code Examples
Example 1: All Three Listeners
// 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.
// 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 (
initStateof the root widget). - Route all three into one handler function so behaviour is consistent.
- Put the information your app needs in
data;notificationis just for display.
Practice Questions
- Which listener handles a message while the app is open?
- The app is closed and the user taps a notification. Which API tells you?
- Why is
getInitialMessagenot a stream? - Where do your own key-value pairs arrive?
Practice Answers
FirebaseMessaging.onMessage.FirebaseMessaging.instance.getInitialMessage().- The app can only be launched once: it answers a single startup question.
message.data.
Key Takeaways
- Foreground →
onMessage; background tap →onMessageOpenedApp; launch tap →getInitialMessage(). - Android shows nothing in the foreground: you decide what to show.
RemoteMessagehasnotification(display) anddata(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
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
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')),
);
}
}