HomeBlogHow to Integrate Push Notifications into...

Engineering Guide · 8 min read · August 18, 2026

How to Integrate Push Notifications into Flutter Applications

Following basic Firebase quickstarts gets a test message onto an Android emulator, then breaks in production on iOS killed-state deep links, foreground banners, and stale device tokens. This step-by-step developer guide covers the full Flutter push pipeline: APNs .p8 auth, foreground vs background isolates, go_router navigation across all three app states, and backend queue hygiene.

Author
Smit Desai
Published
August 18, 2026
Read time
8 min read
Topic
Mobile Apps
Services
Custom Web · Mobile Apps · All Services

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)

  1. In Apple Developer Console, create a single APNs Authentication Key (.p8). Unlike legacy .p12 certificates, .p8 keys do not expire annually and work across both sandbox and production environments.
  2. Upload the .p8 key, Key ID, and Team ID inside Firebase Console → Project Settings → Cloud Messaging.
  3. 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_version
  • last_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):

  1. 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.
  2. 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 ticket 902.
  3. Auth guard compatibility: Verify tapping a notification while logged out safely holds the route or redirects cleanly without crashing.
  4. iOS getAPNSToken() guard: On initial iOS launch, wait briefly if getAPNSToken() is null before calling getToken(), or rely on onTokenRefresh.
  5. Payload size: Keep total FCM data + notification payloads well under 4 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.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Cross-Platform & Native

Mobile App Development Services

Production iOS and Android apps built with Flutter, React Native, Swift, and Kotlin alongside scalable Laravel/Node backends.

Interactive Tool · Estimate Scope

Mobile App Cost Estimator

Calculate week-by-week scope for customer apps, offline sync, push notifications, and App Store / Google Play launches.

01 — Frequently asked questions

mobile apps

Why do FCM notifications arrive on Android but silently fail on iOS?

On iOS, Firebase Cloud Messaging routes through Apple Push Notification service (APNs). Missing the APNs .p8 authentication key in Firebase Console, forgetting the Push Notifications capability in Xcode, or neglecting to wait for getAPNSToken() before reading the FCM token are the three most common causes.

Why doesn't Flutter show a notification banner when the app is in the foreground?

By default, both iOS and Android suppress visual notification banners while your app is open on screen. To display an alert while foregrounded, listen to FirebaseMessaging.onMessage and render a banner using flutter_local_notifications (or call setForegroundNotificationPresentationOptions on iOS).

How do I prevent memory or plugin errors in the Flutter background message handler?

The background handler runs in its own isolated Dart VM without access to your UI widget tree, Provider/Riverpod state, or BuildContext. Always annotate it as a top-level function with @pragma('vm:entry-point') and initialize any required storage plugins inside that function.

How should our backend store and clean up FCM device tokens?

Store tokens in a dedicated user_devices table (one user can own multiple phones/tablets) keyed by device token and platform. Send notifications asynchronously via a background queue and delete tokens immediately whenever FCM returns UNREGISTERED or INVALID_ARGUMENT.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.