Before you begin
Install and initialize the Firebase SDKs for Flutter if you haven’t already done so.
Install the plugin
flutter pub add firebase_messaging
Receive messages in a Flutter app
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
final notificationSettings =
await FirebaseMessaging.instance.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: true,
sound: true,
);
print(
'APNS User granted permission: ${notificationSettings.authorizationStatus}');
// For apple platforms, ensure the APNS token is available before making any FCM plugin API calls
// final apnsToken = await FirebaseMessaging.instance.getAPNSToken();
final apnsToken = await getToken();
debugPrint("APNS Token: $apnsToken");
if (apnsToken != null) {
debugPrint("APNS Token: $apnsToken");
// APNS token is available, make FCM plugin API requests...
}
//Foreground message handling
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Got a message whilst in the foreground!');
print('Message data: ${message.data}');
if (message.notification != null) {
print('Message also contained a notification: ${message.notification}');
}
});
//Background message handling
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(const MainApp());
}
Future<String?> getToken() async {
String? token = await FirebaseMessaging.instance.getToken();
print("FCM Token: $token");
return token;
}
//Background message handling
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp();
print("Handling a background message: ${message.messageId}");
}
Send a test notification message
- Install and run the app on the target device. On Apple devices, you’ll need to accept the request for permission to receive remote notifications.
- Make sure the app is in the background on the device.
- In the Firebase console, open the Messaging page.
- If this is your first message, select Create your first campaign.
- Select Firebase Notification messages and select Create.
- Otherwise, on the Campaigns tab, select New campaign and then Notifications.
- Enter the message text. All other fields are optional.
- Select Send test message from the right pane.
- In the field labeled Add an FCM registration token, enter the registration token you obtained in a previous section of this guide.
- Select Test.