------------------------- | Push Notification Demo | ------------------------- | | | Last message received:| | | | <No message yet> | | | -------------------------
Push notifications (FCM) in Flutter - Mini App: Build & Ship
import 'package:flutter/material.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: PushNotificationDemo(), ); } } class PushNotificationDemo extends StatefulWidget { const PushNotificationDemo({super.key}); @override State<PushNotificationDemo> createState() => _PushNotificationDemoState(); } class _PushNotificationDemoState extends State<PushNotificationDemo> { String _message = '<No message yet>'; @override void initState() { super.initState(); // TODO: Add Firebase Messaging initialization and listeners here } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Push Notification Demo')), body: Center( child: Padding( padding: const EdgeInsets.all(16), child: Text('Last message received:\n\n$_message', textAlign: TextAlign.center), ), ), ); } }
import 'package:flutter/material.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async { // This handler runs when app is in background or terminated print('Background message received: ${message.messageId}'); } void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: PushNotificationDemo(), ); } } class PushNotificationDemo extends StatefulWidget { const PushNotificationDemo({super.key}); @override State<PushNotificationDemo> createState() => _PushNotificationDemoState(); } class _PushNotificationDemoState extends State<PushNotificationDemo> { String _message = '<No message yet>'; final FirebaseMessaging _messaging = FirebaseMessaging.instance; @override void initState() { super.initState(); _requestPermission(); _listenForegroundMessages(); } void _requestPermission() async { NotificationSettings settings = await _messaging.requestPermission( alert: true, badge: true, sound: true, ); print('User granted permission: ${settings.authorizationStatus}'); } void _listenForegroundMessages() { FirebaseMessaging.onMessage.listen((RemoteMessage message) { String notificationBody = message.notification?.body ?? 'No body'; setState(() { _message = notificationBody; }); print('Foreground message received: $notificationBody'); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Push Notification Demo')), body: Center( child: Padding( padding: const EdgeInsets.all(16), child: Text('Last message received:\n\n$_message', textAlign: TextAlign.center), ), ), ); } }
This Flutter app uses Firebase Cloud Messaging (FCM) to receive push notifications.
First, Firebase is initialized in main(). We register a background message handler _firebaseMessagingBackgroundHandler to handle messages when the app is not in the foreground.
In the stateful widget, we request notification permissions from the user using requestPermission(). This is important on iOS and Android 13+.
We listen for messages arriving while the app is open using FirebaseMessaging.onMessage. When a message arrives, we update the screen text with the notification body.
Background and terminated messages are logged to the console by the background handler.
This setup covers the basic flow to receive and display FCM push notifications in a Flutter app.
------------------------- | Push Notification Demo | ------------------------- | | | Last message received:| | | | Hello from FCM! | | | -------------------------
Practice
What is the main purpose of using Firebase Cloud Messaging (FCM) in a Flutter app?
Solution
Step 1: Understand FCM's role
Firebase Cloud Messaging is designed to send messages or notifications to users' devices.Step 2: Identify the correct purpose
Among the options, only sending push notifications matches FCM's main use.Final Answer:
To send push notifications to users even when the app is closed -> Option BQuick Check:
FCM purpose = send push notifications [OK]
- Confusing FCM with UI or local storage
- Thinking FCM manages app navigation
- Assuming FCM only works when app is open
Which Flutter code snippet correctly requests notification permissions on iOS using FirebaseMessaging?
FirebaseMessaging messaging = FirebaseMessaging.instance;
// What code requests permission?
Solution
Step 1: Identify permission request method
The method to ask user permission for notifications is requestPermission().Step 2: Match code snippet
Only await messaging.requestPermission(); correctly requests permissions on iOS.Final Answer:
await messaging.requestPermission(); -> Option AQuick Check:
Permission request = requestPermission() [OK]
- Using getToken() to request permission
- Listening to messages instead of requesting permission
- Subscribing to topics does not request permission
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'));
});
Solution
Step 1: Understand onMessage listener
This listener triggers when a notification arrives while app is open.Step 2: Analyze print statement
It prints 'Message received: ' plus the notification title if it exists, else 'No Title'.Final Answer:
Message received: [notification title] -> Option DQuick Check:
Foreground message prints notification title [OK]
- Ignoring null safety and expecting 'null' string
- Assuming no output if title is missing
- Confusing onMessage with background handlers
Identify the error in this Flutter code snippet for handling FCM token retrieval:
FirebaseMessaging messaging = FirebaseMessaging.instance;
String? token = messaging.getToken();
print('Token: ' + token!);
Solution
Step 1: Check getToken() return type
getToken() returns a Future, so it must be awaited to get the actual token.Step 2: Identify missing await
Code assigns Future to String? without await, causing error.Final Answer:
getToken() returns a Future, so it must be awaited -> Option AQuick Check:
Async methods need await to get values [OK]
- Ignoring async nature of getToken()
- Using ! without checking for null
- Assuming instance is uninitialized without reason
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?
Solution
Step 1: Understand foreground notification behavior
FCM does not show notifications automatically when app is open; you must handle it manually.Step 2: Combine onMessage with local notifications
Listening to onMessage lets you detect incoming messages and then trigger local notifications to show alerts.Step 3: Evaluate other options
getToken only gets device token, subscribeToTopic manages topics, getInitialMessage handles app launch, none show notifications directly.Final Answer:
Listen to FirebaseMessaging.onMessage and call local notification plugin to display notification -> Option CQuick Check:
Foreground notifications need manual local notification trigger [OK]
- Expecting getToken to show notifications
- Thinking subscribeToTopic triggers UI automatically
- Using getInitialMessage for foreground notifications
Ready to prove it?
Pass the test and this pattern moves unknown
