Flutter SDK Setup
Integrate Push Notifications into your Flutter app to receive and handle push notifications on Android and iOS through a single Dart API.
v1.0.8-beta. Not for production use. Pin the exact version. APIs may change without notice.
- Make sure to configure the App ID properly. For additional information see Getting started
- Configure your push credentials in the AppsOnAir console under App Settings → Push Notifications — upload your Firebase service account JSON (Android) and APNs Auth Key (iOS) before sending any notifications.
Requirements
| Minimum | |
|---|---|
| Flutter | 3.47.8+ |
| Dart SDK | 3.13.7+ |
| Android | API 24 (Android 7.0) |
| Kotlin | 1.8+ |
| Gradle | 8.0+ |
| iOS | 15.0 |
| Firebase | google-services.json (Android) |
Basic push — Steps 1–4 only. No iOS extension targets needed:
- Text notifications with title and body
- Tap-to-open and deep links
- Foreground display control
- Images on Android (download automatically via the data payload — no extra setup)
- User targeting, tags, segments, opt-in / opt-out
Advanced push (iOS only) — requires additional extension targets. Skip these if you only need basic push:
| Feature | Additional setup |
|---|---|
| Images on iOS | Notification Service Extension (NSE) |
| Badge auto-increment | NSE + App Group |
| Delivered analytics | NSE + App Group |
| Custom long-press view | NSE + Notification Content Extension (NCE) |
Step 1: Add the Package
- Dart
$ flutter pub add appsonair_flutter_apppush
Step 2: Android Setup
Firebase Configuration
- Open the Firebase Console and add your Android app.
- Download
google-services.jsonand place it inandroid/app/.
Gradle Configuration
Add JitPack to android/settings.gradle.kts:
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
maven("https://jitpack.io")
}
}
allprojects {
repositories {
google()
mavenCentral()
maven("https://jitpack.io")
}
}
Add Google Services plugin to android/build.gradle.kts:
plugins {
id("com.google.gms.google-services") version "4.4.2" apply false
}
Apply it to the app module in android/app/build.gradle.kts:
plugins {
id("com.google.gms.google-services")
}
Notification Icon & Color
The icon and color setup is identical to the native Android SDK. Place your icon in android/app/src/main/res/drawable* and declare both the AppsOnAir and Firebase meta-data entries in android/app/src/main/AndroidManifest.xml.
See Android SDK → Notification Icon & Color for the full setup — the only difference is the android/app/ path prefix on all resource folders.
Step 3: iOS Setup
Capabilities & Info.plist
The required Xcode capabilities (Push Notifications, Background Modes → Remote notifications) and Info.plist keys (AppsonairAppId, CFBundleDisplayName) are the same as the native iOS SDK.
See iOS SDK → Apple Capabilities and iOS SDK → Configure Info.plist for the full setup. The only difference is that all file paths are inside ios/Runner/ instead of the Xcode project root.
AppDelegate.swift
No changes to AppDelegate.swift are required. The plugin registers as the UNUserNotificationCenter delegate automatically via swizzling. The standard AppDelegate.swift generated by flutter create is all that's needed:
import Flutter
import UIKit
@main
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
iOS Dependency Manager
The plugin supports both CocoaPods (default) and Swift Package Manager (requires Flutter ≥ 3.24.0).
- CocoaPods (default)
- Swift Package Manager
No extra steps for the Runner target — just run:
cd ios && pod install
If you are adding the NSE or NCE extension targets, add them as standalone pod targets in your ios/Podfile. The complete Podfile structure looks like this:
target 'Runner' do
use_frameworks!
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end
target 'AppsonairNotificationServiceExtension' do
use_frameworks!
pod 'AppsOnAir-AppPush-ServiceExt', '1.0.9-beta'
end
target 'AppsonairNotificationContentExtension' do
use_frameworks!
pod 'AppsOnAir-AppPush-ContentExt', '1.0.9-beta'
end
Do not use pod 'AppsOnAir-AppPush/ServiceExtension' or pod 'AppsOnAir-AppPush/ContentExtension' (subspec syntax). Subspecs cause "Multiple commands produce AppsOnAir_AppPush.framework" archive failures. Use the standalone pod names shown above.
Requires Flutter ≥ 3.24.0. Enable SPM in Flutter config, then flutter pub get resolves the package automatically — no Podfile configuration needed.
flutter config --enable-swift-package-manager
We recommend migrating to Swift Package Manager — it is Apple's officially maintained dependency manager and receives updates first.
Step 4: Initialize the SDK
Initialize once, as early as possible — preferably in your root widget's initState.
setSilentPushListener before initialize()Silent pushes can arrive while Dart is still starting up. Register your silent push listener before calling initialize() so no events are missed.
import 'package:appsonair_flutter_apppush/appsonair_flutter_apppush.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
@override
void initState() {
super.initState();
_init();
}
Future<void> _init() async {
await AppPushService.Debug.setLogLevel(LogLevel.verbose);
// Register BEFORE initialize() — silent pushes arrive before Dart fully starts
AppPushService.setSilentPushListener((Map<String, dynamic> data) {
print('Silent push received: $data');
});
await AppPushService.initialize();
AppPushService.User.pushSubscription.addObserver((state) {
print('Token: ${state.current.token}');
print('Opted in: ${state.current.isOptedIn}');
});
AppPushService.Notifications.addClickListener((event) {
print('Opened: ${event.notification.title}, action: ${event.actionId}');
});
}
initialize() reads the App ID from AppsonairAppId in the manifest (Android) / Info.plist (iOS). The optional swizzle parameter (default true) controls whether the SDK swizzles UNUserNotificationCenter on iOS — leave it at the default unless you are handling APNs callbacks manually in your own AppDelegate.
initialize() resolvesOn iOS, a tap that opens a killed app is delivered to addClickListener only after initialize() resolves and only if the listener was already registered. Always register listeners immediately after await AppPushService.initialize().
Feature Guides
Listen for Events
Subscribe once and hold the subscription for the app's lifetime.
// Observe token and opt-in state
AppPushService.User.pushSubscription.addObserver((state) {
print('Token: ${state.current.token}');
print('Opted in: ${state.current.isOptedIn}');
});
// Notification received in foreground (after display decision; does NOT fire for silent pushes)
AppPushService.Notifications.addNotificationReceivedListener((event) {
print('Received: ${event.notification.title}');
});
// Notification tapped
AppPushService.Notifications.addClickListener((event) {
final actionId = event.actionId; // null = body tap, else the tapped action's ID
print('Opened: ${event.notification.title}, action: $actionId');
});
// Silent push (data-only) — register BEFORE initialize()
AppPushService.setSilentPushListener((Map<String, dynamic> data) {
print('Silent push: $data');
});
Request Notification Permission
// Check if permission is already granted
final bool granted = await AppPushService.Notifications.permission;
// Check if the system prompt can still be shown (false = permanently denied)
final bool canRequest = await AppPushService.Notifications.canRequestPermission;
if (!granted && canRequest) {
await AppPushService.Notifications.requestPermission();
}
// Permanently denied? Send the user to Settings:
await AppPushService.Notifications.requestPermission(fallbackToSettings: true);
User Identity
await AppPushService.login('user_12345');
await AppPushService.logout();
Tags & Segmentation
await AppPushService.User.addTagWithKey('plan', 'premium');
await AppPushService.User.addTags({'plan': 'premium', 'region': 'us'});
await AppPushService.User.removeTag('plan');
await AppPushService.User.removeTags(['plan', 'region']);
final tags = await AppPushService.User.getTags();
Language
await AppPushService.User.setLanguage('fr'); // ISO 639-1 code
Aliases & Email
await AppPushService.User.addAlias('crm_id', 'CRM-9876');
await AppPushService.User.addAliases({'crm_id': 'CRM-9876'});
await AppPushService.User.removeAlias('crm_id');
await AppPushService.User.removeAliases(['crm_id']);
await AppPushService.User.addEmail('[email protected]');
await AppPushService.User.removeEmail('[email protected]');
Opt-in / Opt-out
await AppPushService.User.pushSubscription.optOut();
await AppPushService.User.pushSubscription.optIn();
final optedIn = await AppPushService.User.pushSubscription.isOptedIn;
Foreground Display
AppPushService.Notifications.addForegroundWillDisplayListener((event) {
// Do nothing → the SDK shows it.
// Call preventDefault() → suppressed entirely, handle it yourself.
event.preventDefault();
});
Badge (Optional)
iOS uses the native badge API. Android uses launcher broadcasts (Samsung, MIUI, ASUS only).
await AppPushService.Notifications.setBadge(5);
await AppPushService.Notifications.incrementBadge(1);
await AppPushService.Notifications.clearBadge();
Error Listener (Optional)
Register a listener to receive SDK errors — permission denied, APNs/FCM registration failures, etc.
AppPushService.addErrorListener((PushError error) {
print(error.code); // typed enum: permissionDenied, apnsRegistrationFailed, etc.
print(error.message); // human-readable description
});
// Remove when no longer needed
AppPushService.removeErrorListener(myListener);
PushErrorCode values:
| Code | Platform | Description |
|---|---|---|
notInitialized | Both | SDK called before initialize() |
permissionDenied | Both | Notification permission not granted |
apnsRegistrationFailed | iOS | APNs token registration failed |
apnsCallbackNotReceived | iOS | No APNs callback — another library may be proxying AppDelegate |
firebaseNotConfigured | Android | google-services.json or Firebase plugin missing |
tokenFetchFailed | Android | FCM token request failed |
installationIdFetchFailed | Android | Firebase Installation ID unavailable |
unknown | Both | Unrecognised code from native SDK |
Managing Delivered Notifications (Optional)
await AppPushService.Notifications.clearAll();
await AppPushService.Notifications.removeNotification('order-4821');
await AppPushService.Notifications.removeGroupedNotifications('orders'); // Android only
iOS: Notification Service Extension (Optional — Rich Push)
Steps 1–4 are all you need for basic push notifications — text, tap-to-open, and deep links. The NSE and NCE are optional extensions you add only when you need:
| Feature | Requires |
|---|---|
| Images in notifications | NSE |
| Badge auto-increment | NSE + App Group |
| Delivered analytics | NSE + App Group |
| Custom expanded view (long-press) | NSE + NCE |
The NSE downloads images, applies payload overrides, updates the badge, and records Delivered analytics. iOS shows no images without it.
The setup steps (target creation, App Group, mutable-content) are the same as the native iOS SDK — see iOS SDK → Notification Service Extension for the full walkthrough.
Flutter-specific notes — linking the SDK to the NSE target:
- CocoaPods
- Swift Package Manager
Add a standalone pod target in ios/Podfile (outside the Runner target):
target 'AppsonairNotificationServiceExtension' do
use_frameworks!
pod 'AppsOnAir-AppPush-ServiceExt', '1.0.9-beta'
end
Then run pod install.
Do not use pod 'AppsOnAir-AppPush/ServiceExtension'. Subspecs cause "Multiple commands produce AppsOnAir_AppPush.framework" archive failures.
Add the package in Xcode → File → Add Package Dependencies:
https://github.com/apps-on-air/appsonair-ios-push-notification
Link AppsOnAir-AppPush-ServiceExt to the NSE target only — never to Runner.
iOS: Notification Content Extension (Optional — Custom Long-Press View)
The NCE replaces the long-press view with the SDK's built-in image + title + body layout. It relies on the NSE to download the image.
The setup steps are the same as the native iOS SDK — see iOS SDK → Notification Content Extension for the full walkthrough.
Flutter-specific notes — linking the SDK to the NCE target:
- CocoaPods
- Swift Package Manager
Add a standalone pod target in ios/Podfile (outside the Runner target):
target 'AppsonairNotificationContentExtension' do
use_frameworks!
pod 'AppsOnAir-AppPush-ContentExt', '1.0.9-beta'
end
Then run pod install.
Do not use pod 'AppsOnAir-AppPush/ContentExtension'. Subspecs cause "Multiple commands produce AppsOnAir_AppPush.framework" archive failures.
Add the package in Xcode → File → Add Package Dependencies (same package URL used for NSE):
https://github.com/apps-on-air/appsonair-ios-push-notification
Link AppsOnAir-AppPush-ContentExt to the NCE target only.
When Notifications Won't Be Delivered
Push delivery can be blocked by OS settings, device state, and manufacturer battery managers — not just your code. For the full breakdown of conditions per platform:
- Android — Doze, App Standby, battery optimization, OEM restrictions, force-stop, and more → Android SDK → When Notifications Won't Be Delivered
- iOS — Low Power Mode, kill mode, Background App Refresh, Apple rate limiting, low battery → iOS SDK → When Notifications Won't Be Delivered
Send silent pushes as data-only FCM payloads (no notification block). If a notification block is present, Firebase renders the notification itself — bypassing the SDK and blocking addNotificationReceivedListener.
Troubleshooting
| Problem | Fix |
|---|---|
| Token never arrives (Android) | Place google-services.json in android/app/ |
| Token never arrives (iOS) | Add Push Notifications capability via Signing & Capabilities |
FIS_AUTH_ERROR in Logcat (Android) | Firebase API key rejected for this build. Follow FIS_AUTH_ERROR |
Token never arrives (Android); Logcat shows c2dm: [-19,ERR_SERVICE_NOT_AVAILABLE,0,0] | The device can't reach Firebase's servers. Follow SERVICE_NOT_AVAILABLE, then force-stop and relaunch the app |
| White square icon (Android) | Add the icon meta-data and a white-on-transparent drawable. See Notification Icon & Color |
| Icon correct in foreground, wrong in background (Android) | Add the com.google.firebase.messaging.default_notification_icon / _color meta-data as well |
| Kill-mode tap not handled | Ensure AppDelegate.swift calls GeneratedPluginRegistrant.register(with: self) and super.application(_:didFinishLaunchingWithOptions:) — the SDK registers automatically via swizzling |
| iOS build fails | Add a blank .swift file to the Xcode project |
| No push in background (Android) | Send a data-only FCM payload — avoid the notification block |
| APNs token not available | Test on a real device; APNs is not supported on the iOS Simulator |
| NSE not invoked | Verify mutable-content: 1 is in the payload and the NSE's Minimum Deployments isn't higher than the device's iOS |
| No images / no Delivered analytics | Both targets must share the same App Group; add AppsOnAirAppGroup to both Info.plist files if you don't use group.<bundle-id>.appsonair |
| NSE never runs, config looks right | Check that the extension is embedded: Runner target → Build Phases → Embed Foundation Extensions |
Build error with an ios/ios/... entitlements path | In the extension's Build Settings, CODE_SIGN_ENTITLEMENTS is relative to ios/. Use AppsonairNotificationServiceExtension/AppsonairNotificationServiceExtension.entitlements, without an ios/ prefix |
| NCE not shown on long-press | aps.category must equal UNNotificationExtensionCategory |
| NCE crashes or is blank | MainInterface.storyboard still present (its default label outlet crashes the extension). Delete it, remove NSExtensionMainStoryboard, and use $(PRODUCT_MODULE_NAME).NotificationViewController |
| Xcode archive fails — "Multiple commands produce framework" | NSE/NCE linked via CocoaPods using subspec syntax (AppsOnAir-AppPush/ServiceExtension) — use standalone pods (AppsOnAir-AppPush-ServiceExt) or switch to SPM |
| Pods not found (iOS) | Run cd ios && pod install after flutter pub get |
Setup Checklist
Android
-
google-services.jsonis inandroid/app/, and the Google Services plugin is applied - JitPack is added to the repositories
-
AppsonairAppId, plus the AppsOnAir and Firebase icon/color meta-data, are inAndroidManifest.xml - A white-on-transparent icon is in
android/app/src/main/res/drawable*, and the color is inres/values/colors.xml
iOS
-
AppsonairAppIdis inios/Runner/Info.plist - Push Notifications and Background Modes → Remote notifications are enabled on Runner
-
AppDelegate.swiftis the standard Flutter template (no manual APNs overrides required — the plugin handles everything via swizzling) - NSE: target added (deployment target matches Runner),
AppsOnAir-AppPush-ServiceExtlinked (via CocoaPods standalone pod or SPM), subclass in place, same App Group on Runner and NSE - NCE (optional): target added,
AppsOnAir-AppPush-ContentExtlinked (via CocoaPods standalone pod or SPM), storyboard removed, category set - Pushes send
mutable-content: 1(andaps.categoryfor the NCE)
Dart
-
AppPushService.initialize()is called afterrunApp - Listeners are added after
initialize()resolves
Log Levels
Set before initialize():
await AppPushService.Debug.setLogLevel(LogLevel.verbose);
await AppPushService.initialize();
Available levels: none, fatal, error, warn, info, debug, verbose.