On this page13 sections
Lecture 005: Messaging Setup & Notification Permission
| Category | 2: Push Notifications |
| Lecture | 005 of 014 |
| Estimated video length | 14 min |
| Target | Flutter 3.44 · Dart 3.12 · FlutterFire (latest) |
| Level | Intermediate |
Firebase Cloud Messaging (FCM) delivers push notifications. Before any can arrive, the app needs the package, iOS needs some Xcode setup, and the user must say yes to notifications.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Practice Questions · Answers · Takeaways · Full Code
Prerequisites
Lecture 004: Firebase initialized in main.
Learning Objectives
- Add
firebase_messaging - Set up iOS: capabilities, background modes and the APNs key
- Ask for notification permission
- Show notifications while the app is open on iOS
- Start a
FirebaseNotificationHandlinghelper class
1. Add firebase_messaging
flutter pub add firebase_messagingOn Android that's all: plus the POST_NOTIFICATIONS permission from Lecture 002.
2. iOS Setup
Apple delivers iOS notifications through APNs (Apple Push Notification service); Firebase hands them over to it. Three steps:
a. Capabilities: Xcode → Runner target → Signing & Capabilities → + Capability:
- Push Notifications
- Background Modes → tick Background fetch and Remote notifications
b. Info.plist: the Background Modes step writes this into ios/Runner/Info.plist:
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>remote-notification</string>
</array>c. APNs key: in the Apple Developer site, Certificates, IDs & Profiles → Keys → +,
tick Apple Push Notifications service (APNs), download the .p8 file. Then Firebase
console → Project settings → Cloud Messaging → Apple app configuration → APNs
Authentication Key → Upload, with the Key ID and your Team ID.
Without the APNs key, iOS never receives anything. Simulators can receive pushes on recent Xcode versions, but test on a real iPhone before trusting it.
3. Ask for Permission
final settings = await FirebaseMessaging.instance.requestPermission(
alert: true,
badge: true,
sound: true,
provisional: false,
);
print('Permission: ${settings.authorizationStatus}');| Option | Meaning |
|---|---|
alert | show the notification banner |
badge | number on the app icon |
sound | play a sound |
provisional | iOS only: deliver quietly without asking first |
On iOS and on Android 13+, this shows the system "Allow notifications?" dialog once. On
older Android, permission is granted automatically. The result is authorized, denied,
notDetermined or provisional.
4. Foreground Presentation (iOS)
By default, iOS hides notifications while the app is open. To show them anyway:
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
alert: true, // show the heads-up banner
badge: true,
sound: true,
);On Android this call does nothing: Lecture 006 explains what Android does instead.
Code Examples
Example 1: The Helper Class
Keep all messaging code in one class:
// lib/firebase_notification_handling.dart
import 'package:firebase_messaging/firebase_messaging.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,
);
}
}// lib/main.dart
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
FirebaseNotificationHandling.registerNotificationPermission();
}
// build(...) as before
}Run on Android 13+ or an iPhone: the permission dialog appears on first launch. The console
prints Notification permission: AuthorizationStatus.authorized after you allow it.
Common Beginner Mistakes
1. Calling requestPermission twice in a row: once is enough; the second call just returns
the same answer.
2. No APNs key: Android works, iOS silently gets nothing. Upload the .p8 key.
3. Missing capabilities: without Push Notifications in Xcode, the iOS token request fails with "no valid 'aps-environment' entitlement".
4. Expecting the dialog again after "Don't allow": the system won't ask twice. The user must enable notifications in the phone's Settings.
Best Practices
- Ask for permission at a moment that makes sense (after onboarding, or when the user turns on a reminder), not on the very first frame.
- Check
authorizationStatusand explain in your UI if notifications are off. - Keep messaging code in one helper class.
Practice Questions
- What is APNs, and why does Firebase need your APNs key?
- Which two Background Modes do you tick?
- On which Android versions does
requestPermissionshow a dialog? - What does
setForegroundNotificationPresentationOptionschange?
Practice Answers
- Apple's push service; Firebase sends iOS notifications through it, so it needs your key.
- Background fetch and Remote notifications.
- Android 13 (API 33) and later.
- Whether iOS shows notifications while the app is in the foreground.
Key Takeaways
flutter pub add firebase_messaging; Android needsPOST_NOTIFICATIONSdeclared.- iOS needs Push Notifications + Background Modes and an APNs key in Firebase.
requestPermissionasks once; check the returned status.- iOS hides foreground notifications unless you set presentation options.
Full Code (Copy-Paste Reference)
Everything the app needs up to and including this lecture, file by file.
lib/firebase_notification_handling.dart
import 'package:firebase_messaging/firebase_messaging.dart';
class FirebaseNotificationHandling {
/// Asks once for notification permission, then (iOS only) tells the OS to
/// show notifications even while the app is in the foreground.
static Future<void> registerNotificationPermission() async {
final settings = await FirebaseMessaging.instance.requestPermission(
alert: true,
badge: true,
sound: true,
);
print('Notification permission: ${settings.authorizationStatus}');
// No-op on Android; on iOS this makes foreground pushes show a banner too.
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}
}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> {
@override
void initState() {
super.initState();
FirebaseNotificationHandling.registerNotificationPermission();
}
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: 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')),
);
}
}