Sub topic 1
How a push notification travels from server to device
Prerequisites
This chapter assumes you have:
- A Flutter project that builds and runs on an emulator or device.
- Working knowledge of Dart
async/awaitandFuture. - A Google account and a Firebase project.
- Familiarity with
AndroidManifest.xmland Xcode capabilities.
The delivery path
Firebase Cloud Messaging (FCM) is Google's free service that carries messages from your server to devices. Your server sends a request to the FCM API, addressed to a device token. FCM then hands the message to the platform's push service: APNs (Apple Push Notification service) for iOS, and Google's transport for Android. The OS delivers it to the device, and your app receives it if it is running or if the OS shows it.
Connecting the app to Firebase
Add the packages, then run flutterfire configure to generate firebase_options.dart.
flutter pub add firebase_core firebase_messaging
dart pub global activate flutterfire_cli
flutterfire configureInitialize Firebase before you use any messaging API:
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'firebase_options.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
runApp(const MaterialApp(home: Scaffold(body: Center(child: Text('FCM demo')))));
}Platform configuration
On Android 13 (API 33) and higher, add the notification permission to android/app/src/main/AndroidManifest.xml:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>On iOS, enable the Push Notifications and Background Modes capabilities in Xcode. In the Firebase console, upload an APNs authentication key (a .p8 file) so FCM can reach Apple's servers.
> The iOS simulator cannot receive remote push notifications. Test on a physical device.
Requesting permission and getting the token
On iOS and Android 13+, the user must grant permission before notifications appear. The token identifies this app instance on this device.
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
Future<void> setUpMessaging() async {
final messaging = FirebaseMessaging.instance;
await messaging.requestPermission(alert: true, badge: true, sound: true);
final token = await messaging.getToken();
debugPrint('FCM token: $token');
messaging.onTokenRefresh.listen((newToken) {
// Send newToken to your server so it stores the current value.
});
}The token can change after reinstalls, app data clears, or certain OS events. Always listen to onTokenRefresh and update your server.
Exercise
Exercise
Why does the app need to send its FCM token to your server?
Show answer
Your server can only address a message to a specific device by its token. Without a current token on the server, the message has no target.