Skip to main content

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.


Beta Release

v1.0.8-beta. Not for production use. Pin the exact version. APIs may change without notice.

Essential Setup
  • 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
Flutter3.47.8+
Dart SDK3.13.7+
AndroidAPI 24 (Android 7.0)
Kotlin1.8+
Gradle8.0+
iOS15.0
Firebasegoogle-services.json (Android)
Basic Push vs Advanced Push (Rich Notifications)

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:

FeatureAdditional setup
Images on iOSNotification Service Extension (NSE)
Badge auto-incrementNSE + App Group
Delivered analyticsNSE + App Group
Custom long-press viewNSE + Notification Content Extension (NCE)

Step 1: Add the Package​

pubspec.yaml
 $ flutter pub add appsonair_flutter_apppush

Step 2: Android Setup​

Firebase Configuration​

  1. Open the Firebase Console and add your Android app.
  2. Download google-services.json and place it in android/app/.

Gradle Configuration​

Add JitPack to android/settings.gradle.kts:

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:

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:

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:

ios/Runner/AppDelegate.swift
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).

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:

ios/Podfile
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
Use standalone pods — not subspecs

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.


Step 4: Initialize the SDK​

Initialize once, as early as possible — preferably in your root widget's initState.

Register 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.

main.dart
import 'package:appsonair_flutter_apppush/appsonair_flutter_apppush.dart';

void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
Root widget initState
@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.

Add listeners after initialize() resolves

On 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.

Events
// 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​

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​

Login / Logout
await AppPushService.login('user_12345');
await AppPushService.logout();

Tags & Segmentation​

Tags
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​

Language
await AppPushService.User.setLanguage('fr');   // ISO 639-1 code

Aliases & Email​

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​

Opt-in / Opt-out
await AppPushService.User.pushSubscription.optOut();
await AppPushService.User.pushSubscription.optIn();
final optedIn = await AppPushService.User.pushSubscription.isOptedIn;

Foreground Display​

Foreground Display
AppPushService.Notifications.addForegroundWillDisplayListener((event) {
// Do nothing → the SDK shows it.
// Call preventDefault() → suppressed entirely, handle it yourself.
event.preventDefault();
});

Badge (Optional)​

Platform Difference

iOS uses the native badge API. Android uses launcher broadcasts (Samsung, MIUI, ASUS only).

Badge
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.

Error Listener
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:

CodePlatformDescription
notInitializedBothSDK called before initialize()
permissionDeniedBothNotification permission not granted
apnsRegistrationFailediOSAPNs token registration failed
apnsCallbackNotReceivediOSNo APNs callback — another library may be proxying AppDelegate
firebaseNotConfiguredAndroidgoogle-services.json or Firebase plugin missing
tokenFetchFailedAndroidFCM token request failed
installationIdFetchFailedAndroidFirebase Installation ID unavailable
unknownBothUnrecognised code from native SDK

Managing Delivered Notifications (Optional)​

Dismiss Notifications
await AppPushService.Notifications.clearAll();
await AppPushService.Notifications.removeNotification('order-4821');
await AppPushService.Notifications.removeGroupedNotifications('orders'); // Android only

iOS: Notification Service Extension (Optional — Rich Push)​

Basic push works without the NSE

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:

FeatureRequires
Images in notificationsNSE
Badge auto-incrementNSE + App Group
Delivered analyticsNSE + 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:

Add a standalone pod target in ios/Podfile (outside the Runner target):

ios/Podfile
target 'AppsonairNotificationServiceExtension' do
use_frameworks!
pod 'AppsOnAir-AppPush-ServiceExt', '1.0.9-beta'
end

Then run pod install.

Use standalone pods — not subspecs

Do not use pod 'AppsOnAir-AppPush/ServiceExtension'. Subspecs cause "Multiple commands produce AppsOnAir_AppPush.framework" archive failures.


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:

Add a standalone pod target in ios/Podfile (outside the Runner target):

ios/Podfile
target 'AppsonairNotificationContentExtension' do
use_frameworks!
pod 'AppsOnAir-AppPush-ContentExt', '1.0.9-beta'
end

Then run pod install.

Use standalone pods — not subspecs

Do not use pod 'AppsOnAir-AppPush/ContentExtension'. Subspecs cause "Multiple commands produce AppsOnAir_AppPush.framework" archive failures.


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:

Silent pushes on Android

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​

ProblemFix
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 handledEnsure AppDelegate.swift calls GeneratedPluginRegistrant.register(with: self) and super.application(_:didFinishLaunchingWithOptions:) — the SDK registers automatically via swizzling
iOS build failsAdd 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 availableTest on a real device; APNs is not supported on the iOS Simulator
NSE not invokedVerify 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 analyticsBoth 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 rightCheck that the extension is embedded: Runner target → Build Phases → Embed Foundation Extensions
Build error with an ios/ios/... entitlements pathIn 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-pressaps.category must equal UNNotificationExtensionCategory
NCE crashes or is blankMainInterface.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.json is in android/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 in AndroidManifest.xml
  • A white-on-transparent icon is in android/app/src/main/res/drawable*, and the color is in res/values/colors.xml

iOS

  • AppsonairAppId is in ios/Runner/Info.plist
  • Push Notifications and Background Modes → Remote notifications are enabled on Runner
  • AppDelegate.swift is the standard Flutter template (no manual APNs overrides required — the plugin handles everything via swizzling)
  • NSE: target added (deployment target matches Runner), AppsOnAir-AppPush-ServiceExt linked (via CocoaPods standalone pod or SPM), subclass in place, same App Group on Runner and NSE
  • NCE (optional): target added, AppsOnAir-AppPush-ContentExt linked (via CocoaPods standalone pod or SPM), storyboard removed, category set
  • Pushes send mutable-content: 1 (and aps.category for the NCE)

Dart

  • AppPushService.initialize() is called after runApp
  • Listeners are added after initialize() resolves

Log Levels​

Set before initialize():

Log Level
await AppPushService.Debug.setLogLevel(LogLevel.verbose);
await AppPushService.initialize();

Available levels: none, fatal, error, warn, info, debug, verbose.