Handle different notification states
mainYou must implement logic to handle how the app responds when a notification is received or tapped in different states:
- Foreground (App Open): Use the
onForegroundMessagecallback. Since the app is already open, you typically display a local notification or update the UI. - Background (App Minimized): Use
onMessageOpenedApp. This is triggered when the user taps a notification while the app is in the background. - Terminated (App Killed): Use
getInitialMessage()to check if the app was launched via a notification tap.
// Handle Foreground
Future<void> _handleForegroundNotification(RemoteMessage message) async {
debugPrint('📬 Foreground notification');
}
// Handle Background/Tapped
Future<void> _handleMessageOpenedApp(RemoteMessage message) async {
debugPrint('📲 App opened from notification');
}
// Handle Terminated
final initialMessage = await _messaging.getInitialMessage();
if (initialMessage != null) {
// Handle the message
}