Bird
Raised Fist0
Fluttermobile~15 mins

Push notifications (FCM) in Flutter - Deep Dive

Choose your learning style10 modes available
Overview - Push notifications (FCM)
What is it?
Push notifications are messages sent by apps to your phone even when the app is not open. Firebase Cloud Messaging (FCM) is a free service by Google that helps developers send these messages to Android and iOS devices. It allows apps to alert users about updates, reminders, or important information instantly. This keeps users engaged and informed without needing to open the app.
Why it matters
Without push notifications, apps would have to rely on users opening them to get updates, which many might forget or ignore. Push notifications help apps stay connected with users in real time, improving user experience and engagement. For example, a messaging app can notify you immediately when someone sends a message, making communication faster and smoother.
Where it fits
Before learning push notifications, you should understand basic Flutter app development and how to use Firebase services. After mastering push notifications, you can explore advanced topics like handling notification actions, customizing notifications, and integrating analytics to track user engagement.
Mental Model
Core Idea
Push notifications are like instant messages from your app, delivered through a cloud service, that reach your device even when the app is closed.
Think of it like...
Imagine your app is a friend who wants to tell you something important. Instead of waiting for you to call them, they send a quick text message that pops up on your phone screen, so you don’t miss it.
┌───────────────┐      ┌───────────────┐      ┌───────────────┐
│   App Server  │─────▶│ Firebase Cloud│─────▶│   User Device │
│ (Sends data)  │      │ Messaging (FCM)│      │ (Receives and │
└───────────────┘      └───────────────┘      │  displays)    │
                                              └───────────────┘
Build-Up - 7 Steps
1
FoundationWhat Are Push Notifications
🤔
Concept: Understanding the basic idea of push notifications and their purpose.
Push notifications are short messages sent by apps to your phone. They appear as alerts or banners even if the app is not open. They help apps communicate important info quickly, like reminders or new messages.
Result
You know that push notifications are messages that pop up on your phone from apps to keep you informed.
Understanding what push notifications are helps you see why apps use them to stay connected with users.
2
FoundationIntroduction to Firebase Cloud Messaging
🤔
Concept: Learning what FCM is and how it helps send push notifications.
Firebase Cloud Messaging (FCM) is a free service by Google that sends push notifications to Android and iOS devices. It acts like a post office that delivers messages from your app server to users’ phones.
Result
You understand that FCM is the tool that makes sending push notifications easy and reliable.
Knowing about FCM shows you the cloud service that handles message delivery, so you don’t have to build it yourself.
3
IntermediateSetting Up FCM in Flutter
🤔Before reading on: Do you think you need to write native Android/iOS code to use FCM in Flutter? Commit to your answer.
Concept: How to connect your Flutter app with Firebase to receive push notifications.
You create a Firebase project and add your Flutter app to it. Then, you add Firebase packages to your Flutter project and initialize Firebase in your app code. This setup lets your app talk to FCM and receive messages.
Result
Your Flutter app is ready to receive push notifications from Firebase.
Understanding the setup process helps you connect your app to the cloud messaging service correctly.
4
IntermediateHandling Notification Permissions
🤔Before reading on: Do you think iOS and Android handle notification permissions the same way? Commit to your answer.
Concept: Learning how to ask users for permission to show notifications and handle their response.
On iOS, apps must ask users for permission to show notifications. On Android, permissions are usually granted by default but can vary by version. You use Flutter plugins to request and check permissions before sending notifications.
Result
Your app politely asks users for permission and respects their choice about notifications.
Knowing how permissions work prevents your notifications from being blocked or ignored.
5
IntermediateReceiving and Displaying Notifications
🤔Before reading on: Do you think notifications appear automatically or need code to handle them? Commit to your answer.
Concept: How to write Flutter code that listens for incoming messages and shows notifications to users.
You use Firebase messaging listeners to detect incoming messages. When a message arrives, your app can show a notification banner or update the app UI. You handle messages differently when the app is in foreground, background, or closed.
Result
Your app shows notifications correctly in all app states.
Understanding message handling ensures users see notifications no matter how they use the app.
6
AdvancedCustomizing Notifications and Actions
🤔Before reading on: Can you add buttons or images to notifications easily? Commit to your answer.
Concept: Adding custom content and interactive buttons to notifications for better user experience.
You can customize notifications with titles, images, sounds, and action buttons. For example, a notification can have a 'Reply' button that opens the app directly to a chat screen. This requires configuring notification payloads and handling user actions in code.
Result
Your notifications become more engaging and useful with custom content and actions.
Knowing how to customize notifications helps create richer user interactions and higher engagement.
7
ExpertManaging Tokens and Message Targeting
🤔Before reading on: Do you think device tokens change over time or stay the same forever? Commit to your answer.
Concept: Understanding device tokens, how to manage them, and how to target specific users or groups.
Each device gets a unique token from FCM to receive messages. Tokens can change, so your app must update the server with new tokens. You can send messages to single devices, groups, or topics. Managing tokens and targeting correctly ensures messages reach the right users.
Result
You can reliably send notifications to intended users and handle token updates gracefully.
Knowing token management prevents lost messages and improves notification delivery accuracy.
Under the Hood
When your app server wants to send a notification, it sends a message to Firebase Cloud Messaging with the target device's token. FCM queues the message and delivers it to the device using platform-specific services (Google Play Services on Android, APNs on iOS). The device receives the message and the app or system displays the notification. Tokens identify devices uniquely and can expire or change, so apps must keep them updated.
Why designed this way?
FCM was designed to offload the complexity of message delivery from app developers. Handling device connections, retries, and platform differences is hard, so Google built FCM as a reliable, scalable cloud service. Using tokens allows targeting specific devices without exposing user data. This design balances ease of use, privacy, and reliability.
┌───────────────┐      ┌───────────────┐      ┌───────────────┐      ┌───────────────┐
│  App Server   │─────▶│ Firebase Cloud│─────▶│ Platform Push │─────▶│ User Device   │
│ (Sends Msg)  │      │ Messaging (FCM)│      │ Service (APNs/│      │ (Receives Msg)│
└───────────────┘      └───────────────┘      │ Google Play)  │      └───────────────┘
                                               └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think push notifications always arrive instantly? Commit to yes or no.
Common Belief:Push notifications are delivered instantly every time without delay.
Tap to reveal reality
Reality:Delivery depends on network conditions, device state, and platform queues. Sometimes notifications are delayed or dropped.
Why it matters:Expecting instant delivery can cause confusion or bugs if your app relies on immediate notification arrival.
Quick: Do you think your app can send notifications without user permission on iOS? Commit to yes or no.
Common Belief:Apps can send push notifications on iOS without asking the user first.
Tap to reveal reality
Reality:iOS requires explicit user permission before showing notifications. Without permission, notifications won’t appear.
Why it matters:Not requesting permission properly means users never see your notifications, reducing app engagement.
Quick: Do you think the device token for FCM is permanent? Commit to yes or no.
Common Belief:The FCM device token never changes once assigned.
Tap to reveal reality
Reality:Tokens can change after app reinstall, device reset, or token refresh events.
Why it matters:Failing to update tokens leads to lost notifications and unhappy users.
Quick: Do you think push notifications can only be used for alerts? Commit to yes or no.
Common Belief:Push notifications are only for showing alerts or messages.
Tap to reveal reality
Reality:They can also carry data silently to update app content or trigger background tasks.
Why it matters:Limiting push notifications to alerts misses powerful use cases like syncing data or improving app responsiveness.
Expert Zone
1
FCM tokens are scoped per app and per device, but also per app instance, meaning multiple tokens can exist for the same user on different devices or app installs.
2
Handling background messages on iOS requires special setup with APNs and silent notifications, which behave differently than Android, affecting reliability.
3
Using topics and device groups for message targeting can simplify sending to many users but requires careful management to avoid over-notifying or missing users.
When NOT to use
Push notifications are not suitable for large data transfers or guaranteed message delivery. For critical real-time communication, consider WebSockets or in-app messaging. Also, avoid push notifications for non-urgent or excessive messages to prevent user annoyance and app uninstalls.
Production Patterns
In production, apps use FCM with analytics to track notification opens and conversions. They implement token refresh handling to keep user lists updated. Notifications are personalized using user preferences and segmented targeting. Many apps combine push notifications with in-app messaging for a seamless user experience.
Connections
Event-driven Architecture
Push notifications are a form of event-driven communication where events trigger messages to users.
Understanding event-driven systems helps grasp how notifications respond to app or server events asynchronously.
Email Marketing
Both push notifications and email marketing deliver messages to users to engage them.
Knowing email marketing strategies can improve how you design notification content and timing for better user engagement.
Postal Mail System
Push notifications use a delivery system similar to postal mail, with senders, a delivery service, and recipients.
Recognizing this helps understand message routing, addressing (tokens), and delivery reliability challenges.
Common Pitfalls
#1Not requesting notification permission on iOS.
Wrong approach:FirebaseMessaging.instance.getToken(); // Without asking permission first
Correct approach:await FirebaseMessaging.instance.requestPermission(); String? token = await FirebaseMessaging.instance.getToken();
Root cause:Assuming iOS grants notification permission by default leads to no notifications shown.
#2Ignoring token refresh events and not updating server.
Wrong approach:Only get token once at app start and never update server.
Correct approach:FirebaseMessaging.instance.onTokenRefresh.listen((newToken) { // Send newToken to server });
Root cause:Not handling token changes causes notifications to fail silently.
#3Handling notifications only when app is open (foreground).
Wrong approach:Listening only to onMessage stream and ignoring background or terminated states.
Correct approach:Implement background message handler and configure platform-specific settings to handle all app states.
Root cause:Misunderstanding app lifecycle states causes missed notifications when app is not active.
Key Takeaways
Push notifications let apps send timely messages to users even when the app is closed, improving engagement.
Firebase Cloud Messaging (FCM) is a free, reliable service that handles delivering notifications across Android and iOS.
Proper setup includes initializing Firebase, requesting permissions, and handling tokens and message reception in all app states.
Customizing notifications and managing tokens carefully ensures users get relevant, interactive messages without errors.
Understanding platform differences and delivery mechanics helps build robust notification features that delight users.

Practice

(1/5)
1.

What is the main purpose of using Firebase Cloud Messaging (FCM) in a Flutter app?

easy
A. To create user interfaces with Flutter widgets
B. To send push notifications to users even when the app is closed
C. To store user data locally on the device
D. To manage app navigation between screens

Solution

  1. Step 1: Understand FCM's role

    Firebase Cloud Messaging is designed to send messages or notifications to users' devices.
  2. Step 2: Identify the correct purpose

    Among the options, only sending push notifications matches FCM's main use.
  3. Final Answer:

    To send push notifications to users even when the app is closed -> Option B
  4. Quick Check:

    FCM purpose = send push notifications [OK]
Hint: FCM is for messaging, not UI or storage [OK]
Common Mistakes:
  • Confusing FCM with UI or local storage
  • Thinking FCM manages app navigation
  • Assuming FCM only works when app is open
2.

Which Flutter code snippet correctly requests notification permissions on iOS using FirebaseMessaging?

FirebaseMessaging messaging = FirebaseMessaging.instance;
// What code requests permission?
easy
A. await messaging.requestPermission();
B. messaging.getToken();
C. FirebaseMessaging.onMessage.listen();
D. await messaging.subscribeToTopic('news');

Solution

  1. Step 1: Identify permission request method

    The method to ask user permission for notifications is requestPermission().
  2. Step 2: Match code snippet

    Only await messaging.requestPermission(); correctly requests permissions on iOS.
  3. Final Answer:

    await messaging.requestPermission(); -> Option A
  4. Quick Check:

    Permission request = requestPermission() [OK]
Hint: Permission request always uses requestPermission() method [OK]
Common Mistakes:
  • Using getToken() to request permission
  • Listening to messages instead of requesting permission
  • Subscribing to topics does not request permission
3.

Given this Flutter code snippet, what will be printed when a push notification is received while the app is in the foreground?

FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  print('Message received: ' + (message.notification?.title ?? 'No Title'));
});
medium
A. Message received: No Title
B. Message received: null
C. No output printed
D. Message received: [notification title]

Solution

  1. Step 1: Understand onMessage listener

    This listener triggers when a notification arrives while app is open.
  2. Step 2: Analyze print statement

    It prints 'Message received: ' plus the notification title if it exists, else 'No Title'.
  3. Final Answer:

    Message received: [notification title] -> Option D
  4. Quick Check:

    Foreground message prints notification title [OK]
Hint: ?.title returns title or null, ?? provides fallback [OK]
Common Mistakes:
  • Ignoring null safety and expecting 'null' string
  • Assuming no output if title is missing
  • Confusing onMessage with background handlers
4.

Identify the error in this Flutter code snippet for handling FCM token retrieval:

FirebaseMessaging messaging = FirebaseMessaging.instance;
String? token = messaging.getToken();
print('Token: ' + token!);
medium
A. getToken() returns a Future, so it must be awaited
B. token cannot be null, so ! is unnecessary
C. FirebaseMessaging.instance is not initialized
D. print statement syntax is incorrect

Solution

  1. Step 1: Check getToken() return type

    getToken() returns a Future, so it must be awaited to get the actual token.
  2. Step 2: Identify missing await

    Code assigns Future to String? without await, causing error.
  3. Final Answer:

    getToken() returns a Future, so it must be awaited -> Option A
  4. Quick Check:

    Async methods need await to get values [OK]
Hint: Async calls must use await or then() [OK]
Common Mistakes:
  • Ignoring async nature of getToken()
  • Using ! without checking for null
  • Assuming instance is uninitialized without reason
5.

You want to show a local notification when a push notification arrives while the app is in the foreground. Which approach correctly combines FirebaseMessaging with Flutter Local Notifications?

hard
A. Use FirebaseMessaging.subscribeToTopic to trigger local notifications automatically
B. Only use FirebaseMessaging.getToken to show notifications
C. Listen to FirebaseMessaging.onMessage and call local notification plugin to display notification
D. Call local notifications plugin inside FirebaseMessaging.getInitialMessage

Solution

  1. Step 1: Understand foreground notification behavior

    FCM does not show notifications automatically when app is open; you must handle it manually.
  2. Step 2: Combine onMessage with local notifications

    Listening to onMessage lets you detect incoming messages and then trigger local notifications to show alerts.
  3. Step 3: Evaluate other options

    getToken only gets device token, subscribeToTopic manages topics, getInitialMessage handles app launch, none show notifications directly.
  4. Final Answer:

    Listen to FirebaseMessaging.onMessage and call local notification plugin to display notification -> Option C
  5. Quick Check:

    Foreground notifications need manual local notification trigger [OK]
Hint: Use onMessage + local notifications for foreground alerts [OK]
Common Mistakes:
  • Expecting getToken to show notifications
  • Thinking subscribeToTopic triggers UI automatically
  • Using getInitialMessage for foreground notifications
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard