Back to results for “Deep Linking in Flutter”
Flutter › Push Notifications in Flutter (FCM)

How should you properly handle a push notification differently depending on whether your app is currently genuinely running in the foreground, running in the background, or completely fully terminated?

Intermediate

Answer

Firebase Cloud Messaging genuinely provides several genuinely separate distinct callback handlers depending on your app's own current specific state, with onMessage properly handling a notification received while the app is genuinely currently actively running in the foreground, letting you display your own genuinely custom in app notification banner instead of relying on the operating system's own default one, onMessageOpenedApp properly handling the case where a user actually taps a notification that had brought the app back from a background state, and a separate top level background message handler properly handling messages received while the app is genuinely completely terminated.
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  showInAppBanner(message.notification?.title);
});

FirebaseMessaging.onMessageOpenedApp.listen((message) {
  navigateToRelevantScreen(message.data);
});
Real-world example A messaging app displays a genuinely custom in app banner when a new message notification arrives while a user is actively using the app in the foreground, while properly navigating them directly to the relevant specific chat screen if they instead tap that same notification while the app was genuinely running in the background.

Common follow-ups: Why does the completely terminated app state genuinely require its own genuinely separate top level background handler function?;How do you actually properly test each one of these several genuinely different specific app states during active development?