Sub topic 11
Displaying foreground notifications with a local notifications plugin
Prerequisites
This chapter assumes you have completed the earlier chapters of this tutorial:
- Firebase is initialized in your app.
- Notification permission is requested.
- You can receive messages through
FirebaseMessaging.onMessage. - You know the difference between notification messages and data messages.
The problem: Android stays silent in the foreground
When a notification message arrives and your app is in the background or terminated, the operating system draws the notification. When the app is in the foreground, behavior differs by platform:
- On Android, FCM delivers the message to
onMessageand shows nothing. The system tray is skipped. - On iOS, the message is also delivered to
onMessage, and nothing is shown unless you opt in.
If you want a banner while the user is inside the app, you have to draw it yourself. There are two ways to do that:
- Show an in-app widget, such as a
SnackBaror a custom overlay. - Raise a real system notification from the app with a local notifications plugin. It looks the same as a push notification, lands in the notification tray, and can be tapped later.
This chapter covers the second option with the flutter_local_notifications package. A local notification is one created on the device by your own code. No server and no network are involved.
Where local notifications fit
Add the dependency
Add the plugin next to the Firebase packages:
dependencies:
firebase_core: ^3.0.0
firebase_messaging: ^15.0.0
flutter_local_notifications: ^19.0.0The examples use the 19.x API, where initialize and show take positional arguments. Newer major versions have changed some of these signatures to named parameters. Check the changelog of the version you install if the compiler rejects a call.
Android: channels
Since Android 8, every notification belongs to a notification channel. The user controls each channel's sound and importance in system settings. A channel's importance decides whether a notification pops up as a heads-up banner. Without a high-importance channel, your foreground notification may appear silently in the tray only.
You create the channel once, and Android then remembers it:
- Changing its importance in code later has no effect on devices that already created it.
- To change importance, use a new channel ID, or reinstall the app while testing.
You can also make background FCM notifications use the same channel. Add this inside <application> in AndroidManifest.xml:
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="high_importance_channel" />Without it, FCM uses its own default channel, and foreground and background notifications behave differently.
Android 13 and later also require the POST_NOTIFICATIONS runtime permission. You already requested it through requestPermission. If the user denied it, show produces nothing and throws no error.
Initialize the plugin
Initialize the plugin once at startup, after Firebase.initializeApp. The code below creates the channel, registers a tap callback, and checks whether a local notification launched the app.
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
const AndroidNotificationChannel highImportanceChannel =
AndroidNotificationChannel(
'high_importance_channel',
'High importance notifications',
description: 'Messages shown while the app is open.',
importance: Importance.high,
);
final FlutterLocalNotificationsPlugin localNotifications =
FlutterLocalNotificationsPlugin();
Future<void> initLocalNotifications({
required void Function(String route) onRoute,
}) async {
const initSettings = InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
iOS: DarwinInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
),
);
await localNotifications.initialize(
initSettings,
onDidReceiveNotificationResponse: (NotificationResponse response) {
final payload = response.payload;
if (payload != null && payload.isNotEmpty) onRoute(payload);
},
);
await localNotifications
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(highImportanceChannel);
// A local notification that was tapped while the app was terminated.
final launch = await localNotifications.getNotificationAppLaunchDetails();
if (launch?.didNotificationLaunchApp ?? false) {
final payload = launch!.notificationResponse?.payload;
if (payload != null && payload.isNotEmpty) onRoute(payload);
}
}Three details in this code matter:
- The Darwin settings disable the plugin's own permission prompts. FCM's
requestPermissionalready asked, and asking twice is confusing for the user. @mipmap/ic_launchermust exist inandroid/app/src/main/res. A missing icon makesshowfail on Android with aninvalid_iconerror.- The launch-details check covers a case that
getInitialMessagedoes not. A local notification you raised while the app was open stays in the tray. If the user kills the app and later taps it, Android cold-starts the app with no FCM message attached.
Show a notification from onMessage
Now listen to onMessage and call show:
void showForegroundNotifications() {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
final notification = message.notification;
if (notification == null) return; // data-only: nothing to display
// On iOS the system shows the banner; see the next section.
if (defaultTargetPlatform != TargetPlatform.android) return;
final id = DateTime.now().millisecondsSinceEpoch.remainder(0x7FFFFFFF);
localNotifications.show(
id,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
highImportanceChannel.id,
highImportanceChannel.name,
channelDescription: highImportanceChannel.description,
importance: Importance.high,
priority: Priority.high,
icon: '@mipmap/ic_launcher',
),
),
payload: message.data['route'],
);
});
}Points to check in this listener:
- Notification IDs must be 32-bit integers. If you reuse an ID, the new notification replaces the old one. That is useful for chat threads, where one conversation should show one entry. It is a bug when you want separate entries.
- The payload is a string. FCM
datavalues are already strings. If you need several fields, encode them withjsonEncodeand decode them in the tap callback. nullnotification means data-only. Decide whether your app should build a notification from the data fields. If it should, readmessage.data['title']andmessage.data['body']yourself.
iOS: use presentation options instead
iOS can show a foreground banner without any local notification. One call enables it for FCM messages:
Future<void> enableIosForegroundPresentation() async {
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
}Call this once in main after Firebase initializes. Do not combine it with a local show on iOS. You would get two banners for each message. This is why the listener above exits early on non-Android platforms. If you need custom content on iOS, leave the presentation options off and let the plugin show the notification instead. Then you must remove the early return and add DarwinNotificationDetails to NotificationDetails.
Wiring it together
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
await enableIosForegroundPresentation();
await initLocalNotifications(onRoute: (route) => debugPrint('Go to $route'));
showForegroundNotifications();
runApp(const MyApp());
}Replace the debugPrint with your navigation call. The chapter on payload navigation covers that.
Common errors
| Symptom | Likely cause |
|---|---|
| Nothing appears on Android, no error | `POST_NOTIFICATIONS` denied, or the channel is blocked in system settings |
| Notification appears only in the tray, with no banner | Channel importance is below `high`, or the channel was created earlier with a lower value |
| `invalid_icon` exception | The drawable named in `AndroidInitializationSettings` does not exist |
| Two banners on iOS | Presentation options are on and `show` is also called |
| Tap does nothing after a cold start | The launch-details check is missing, or `initialize` ran after the first frame was handled |
| New notification replaces an old one | Notification ID reused |
Background data-only messages
Everything above runs in the main isolate, while the app is open. A data-only message that arrives in the background goes to your top-level background handler, which runs in a separate isolate. If you want to display something for that message, create a new FlutterLocalNotificationsPlugin inside the handler and initialize it there. The main isolate's instance is not shared. Do not call show for messages that include a notification part. The system has already shown those, and you would duplicate them.
Exercise
On Android, your app shows each foreground FCM message with localNotifications.show(0, ...). A user receives three messages in a row while the app is open and sees only the last one in the tray. What is the cause, and how do you fix it?
Show answer
Every call uses notification ID 0, so each new notification replaces the previous one. Generate a distinct 32-bit integer for each message, for example DateTime.now().millisecondsSinceEpoch.remainder(0x7FFFFFFF). If you want one entry per conversation instead, derive the ID from a stable key such as the chat ID.
Exercise
You enabled setForegroundNotificationPresentationOptions on iOS and also call localNotifications.show for every onMessage event on both platforms. What does an iOS user see, and what is the smallest change that fixes it?
Show answer
The user sees two banners for each message: one from the system presentation options and one from the plugin. The smallest fix is to return early from the onMessage listener when defaultTargetPlatform is not TargetPlatform.android, so only Android uses the plugin.