Every mobile tutorial makes push notifications look like a ten-minute Firebase install. Then you ship to TestFlight and real issues appear: iOS drops notifications when the app is swiped away, tapping a notification from cold start opens the home screen instead of the order detail page, and foreground messages disappear silently.
Reliable push notifications are a three-part contract between Flutter's isolate lifecycle, Apple/Google delivery gateways, and your backend queue. Here is how to wire all three cleanly so notifications arrive reliably across Android and iOS.
1. Platform Setup: APNs Keys and Android 13+ Permissions
Before touching Dart code, lock down the native prerequisites so you are not debugging missing capabilities later.
iOS (APNs .p8 Key)
- In Apple Developer Console, create a single APNs Authentication Key (
.p8). Unlike legacy.p12certificates,.p8keys do not expire annually and work across both sandbox and production environments. - Upload the
.p8key, Key ID, and Team ID inside Firebase Console → Project Settings → Cloud Messaging. - In Xcode (
ios/Runner/Runner.xcodeproj), add Push Notifications and Background Modes → Remote notifications under Signing & Capabilities.
Android (POST_NOTIFICATIONS & Channels)
Starting with Android 13 (API 33), apps must explicitly request the POST_NOTIFICATIONS runtime permission. Furthermore, high-priority heads-up notifications require a named NotificationChannel with Importance.max created via flutter_local_notifications on app startup; otherwise Android demotes alerts silently to the notification shade.
2. Handling All Three App States in Flutter
A Flutter app receives push payloads in three distinct runtime states, and each triggers a different callback:
| App State | Payload Type | Handler / Entry Point | Banner Shown Automatically? |
|---|---|---|---|
| Foreground | notification + data |
FirebaseMessaging.onMessage |
No (must render locally or enable iOS foreground presentation) |
| Background (minimized) | notification + data |
onBackgroundMessage + onMessageOpenedApp on tap |
Yes (by OS) |
| Terminated (killed) | notification + data |
onBackgroundMessage + getInitialMessage() on launch |
Yes (by OS) |
The Background Isolate Trap
In Flutter, when a silent/data notification wakes a backgrounded or terminated app, Android/iOS spawns a separate headless Dart isolate. Do not reference Riverpod providers, GetIt singletons initialized in main(), or Navigator keys inside your background handler.
@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// Runs in an isolated Dart VM — initialize Firebase here if needed.
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
// Only perform lightweight persistence or local badge updates here.
debugPrint('Background message ID: ${message.messageId}');
}
Register FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler); at the top of main() before runApp(). Keep your Dart isolates clean and avoid heavy synchronous work here, following the Flutter performance best practices.
3. Rendering Foreground Notifications with flutter_local_notifications
Because OS conventions hide incoming system banners while the user is actively looking at your app, pair firebase_messaging with flutter_local_notifications to show consistent foreground alerts—and unify tap routing.
class PushNotificationService {
PushNotificationService(this._router);
final GoRouter _router;
final _localNotifications = FlutterLocalNotificationsPlugin();
static const _highImportanceChannel = AndroidNotificationChannel(
'high_importance_channel',
'Order & Account Alerts',
description: 'Real-time updates requiring immediate attention.',
importance: Importance.max,
);
Future<void> init() async {
await FirebaseMessaging.instance.requestPermission(
alert: true,
badge: true,
sound: true,
);
// Ensure Android channel exists before any notification arrives
final androidPlugin = _localNotifications
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>();
await androidPlugin?.createNotificationChannel(_highImportanceChannel);
const initSettings = InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
iOS: DarwinInitializationSettings(),
);
await _localNotifications.initialize(
initSettings,
onDidReceiveNotificationResponse: (response) {
if (response.payload != null) {
_handleRoutePayload(jsonDecode(response.payload!) as Map<String, dynamic>);
}
},
);
FirebaseMessaging.onMessage.listen(_showForegroundNotification);
FirebaseMessaging.onMessageOpenedApp.listen((msg) => _handleRoutePayload(msg.data));
// Handle tap when app was completely terminated
final initialMessage = await FirebaseMessaging.instance.getInitialMessage();
if (initialMessage != null) {
_handleRoutePayload(initialMessage.data);
}
}
Future<void> _showForegroundNotification(RemoteMessage message) async {
final notification = message.notification;
if (notification == null) return;
await _localNotifications.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
_highImportanceChannel.id,
_highImportanceChannel.name,
channelDescription: _highImportanceChannel.description,
importance: Importance.max,
priority: Priority.high,
),
iOS: const DarwinNotificationDetails(presentAlert: true, presentSound: true),
),
payload: jsonEncode(message.data),
);
}
void _handleRoutePayload(Map<String, dynamic> data) {
final route = data['route'] as String?;
if (route != null && route.startsWith('/')) {
_router.go(route);
}
}
}
Notice how getInitialMessage() runs once during initialization—or better yet, store any pending deep link in your router state until authentication/splash initialization finishes so an unauthenticated cold launch redirects to login first, then forwards to /orders/4821.
4. Token Lifecycle and Backend Delivery Hygiene
Hardcoding a single fcm_token column onto your users table breaks the moment a user logs in on both an iPhone and an iPad, or logs out on a shared work tablet.
Design a Dedicated device_tokens Table
Track tokens per device installation:
user_id(foreign key)token(unique string)platform(ios|android)app_versionlast_seen_at
In Flutter, always listen to FirebaseMessaging.instance.onTokenRefresh.listen(syncTokenToApi) in addition to uploading the initial token after login. On logout, hit DELETE /api/device-tokens/{token} before clearing the user's auth token so the previous user stops receiving private notifications.
Queue Dispatch & Prune Dead Tokens
Never send FCM HTTP v1 API calls synchronously inside a web request controller—one slow Google endpoint stalls your checkout or chat response. Dispatch notifications through a background worker (Laravel Queues, Celery, or BullMQ). When FCM returns 404 UNREGISTERED or 400 INVALID_ARGUMENT, immediately delete that row from device_tokens to keep delivery metrics clean.
If you are pairing Flutter with a versioned API backend, check our mobile app development guide for global startups and mobile app development services for full backend integration patterns.
5. Production Checklist Before Release
Run through these five checks on physical iOS and Android devices (not simulators, which cannot receive real APNs pushes):
- Permission priming: Ask for notification permission right after a clear user action (e.g., placing an order or toggling alerts), not on the very first splash screen.
- Killed-state deep link: Force-quit the app, send a push with
{"route": "/tickets/902"}, tap the banner, and verify the app lands directly on ticket902. - Auth guard compatibility: Verify tapping a notification while logged out safely holds the route or redirects cleanly without crashing.
- iOS
getAPNSToken()guard: On initial iOS launch, wait briefly ifgetAPNSToken()is null before callinggetToken(), or rely ononTokenRefresh. - Payload size: Keep total FCM
data+notificationpayloads well under4 KB.
Shipping Reliable Mobile Infrastructure with SmitDev
Push notifications are rarely isolated—they tie directly into background queues, user permissions, deep linking, and real-time product workflows. At SmitDev, we build production Flutter apps and scalable Laravel/FastAPI backends for teams across the US, UK, Europe, UAE, Australia, and Singapore, backed by 170+ shipped case studies since 2017.
If your team needs help debugging broken iOS/Android push delivery, wiring real-time notification pipelines, or accelerating your mobile roadmap, you can bring in dedicated senior engineering at $55/day (8–9 hours of focused work) or $1,999/month for full-time delivery—or hire a dedicated developer aligned with your time zone.
Reach out here to walk through your Flutter architecture and get your release pipeline unstuck.