On this page13 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Add firebase_messaging
  4. 2. iOS Setup
  5. 3. Ask for Permission
  6. 4. Foreground Presentation (iOS)
  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 005: Messaging Setup & Notification Permission

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

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 FirebaseNotificationHandling helper class

1. Add firebase_messaging

bash
flutter pub add firebase_messaging

On 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:

xml
<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

dart
final settings = await FirebaseMessaging.instance.requestPermission(
  alert: true,
  badge: true,
  sound: true,
  provisional: false,
);
print('Permission: ${settings.authorizationStatus}');
OptionMeaning
alertshow the notification banner
badgenumber on the app icon
soundplay a sound
provisionaliOS 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:

dart
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:

dart
// 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,
    );
  }
}
dart
// 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 authorizationStatus and explain in your UI if notifications are off.
  • Keep messaging code in one helper class.

Practice Questions

  1. What is APNs, and why does Firebase need your APNs key?
  2. Which two Background Modes do you tick?
  3. On which Android versions does requestPermission show a dialog?
  4. What does setForegroundNotificationPresentationOptions change?

Practice Answers

  1. Apple's push service; Firebase sends iOS notifications through it, so it needs your key.
  2. Background fetch and Remote notifications.
  3. Android 13 (API 33) and later.
  4. Whether iOS shows notifications while the app is in the foreground.

Key Takeaways

  • flutter pub add firebase_messaging; Android needs POST_NOTIFICATIONS declared.
  • iOS needs Push Notifications + Background Modes and an APNs key in Firebase.
  • requestPermission asks 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

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

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