Flutter SDK Setup
Instructions for adding the OneSignal Flutter SDK to your Flutter app for iOS and Android
Requirements
- iOS: iOS 11+ or iPadOS 11+ device (iPhone, iPad, iPod Touch) to test on. Xcode 14+ simulator works running iOS 16+
- iOS: mac with Xcode 12+
- Android: Android 5.0+ device or emulator with "Google Play Store (Services)" installed
- Configured OneSignal App and Platform
Configure your OneSignal App and Platform
Details on configuring your OneSignal App and Platform (click to expand)
If you haven't already, sign up for a free account on onesignal.com.
You can setup multiple platforms (iOS, Android, Web, Email, SMS) within the same OneSignal App under Settings > Platforms. If you want to create a new app select New App/Website. If this is your first OneSignal app, you will see the next page.
Name your app and organization something recognizable, then select the platform to setup. You can always set up more platforms in this OneSignal App later within Settings > Platforms.
Click Next: Configure Your Platform.
To configure your app, follow the prompts based on the platforms you support.
- Android: Set up your Android Firebase Credentials
- iOS: p8 Authentication Token or p12 Push Notification Certificate
- Amazon: Generate an Amazon API Key
- Huawei: Authorize OneSignal to send Huawei Push
After you setup your credentials, click Save & Continue.
Choose your Apps Target SDK, the click Save & Continue.
Finally, you will be directed to install the SDK and provided your OneSignal App ID. Make sure to save your App ID as you will need it later.
If you need a teammate or your developer to assist, you can click Invite them to the app and select Done when finished.
Continue through the documentation to finish adding OneSignal to your app.
Setup
1. Add SDK
To add the OneSignal Flutter SDK, edit your project's pubspec.yaml
file and add OneSignal to the dependencies list:
dependencies:
onesignal_flutter: ^5.1.2
Run flutter pub get
to install the SDK. Or, if you are using Android Studio, Click Pub get
in the action ribbon at the top of pubspec.yaml.
Now, in your Dart code, you can access OneSignal with:
import 'package:onesignal_flutter/onesignal_flutter.dart';
2. iOS Setup
Open the .xcworkspace
file in Xcode located your project's ios folder.
Select the root project > your main app target > Signing & Capabilities.
If you do not see Push Notifications enabled, click + Capability and add Push Notifications.
Click + Capability again and add Background Modes. Then check Remote notifications.
Add Notification Service Extension
The OneSignalNotificationServiceExtension allows your iOS application to receive rich notifications with images, buttons, and badges. It's also required for OneSignal's Confirmed Delivery analytics features.
In Xcode Select File > New > Target...
Select Notification Service Extension then Next.
Enter the product name as OneSignalNotificationServiceExtension
and press Finish.
Do not activate the scheme on the dialog that is shown after selecting Finish.
Press Cancel on the "Activate scheme" prompt.
Select the OneSignalNotificationServiceExtension target and General settings.
Set Minimum Deployments to be the same value as your Main Application Target. This should be iOS 11 or higher.
Add App Groups
App Groups allow your app and the OneSignalNotificationServiceExtension to communicate when a notification is received, even if your app is not active. This is required for badges and Confirmed Deliveries.
Select your Main App Target > Signing & Capabilities > + Capability > App Groups.
Within App Groups, click the + button.
Set the App Groups container to be group.YOUR_BUNDLE_IDENTIFIER.onesignal
where YOUR_BUNDLE_IDENTIFIER
is the same as your Main Application "Bundle Identifier".
Press OK and repeat for the OneSignalNotificationServiceExtension Target.
Select the OneSignalNotificationServiceExtension Target > Signing & Capabilities > + Capability > App Groups.
Within App Groups, click the + button.
Set the App Groups container to be group.YOUR_BUNDLE_IDENTIFIER.onesignal
where YOUR_BUNDLE_IDENTIFIER
is the same as your Main Application "Bundle Identifier".
DO NOT INCLUDE OneSignalNotificationServiceExtension
.
Optional instructions to setup custom App Group Name (click to expand)
This step is only required if you do not want to use the default app group name (which is group.{your_bundle_id}.onesignal
).
Open your Info.plist
file and add a new OneSignal_app_groups_key
as a String
type.
Enter the group name you checked in the last step as it's value.
Make sure to do the same for the Info.plist
under the OneSignalNotificationServiceExtension
folder.
Add OneSignal SDK to the OneSignalNotificationServiceExtension
In the /ios
directory of your project, open the Podfile
and add the following outside of the main target (should be at the same level as your main target):
target 'OneSignalNotificationServiceExtension' do
use_frameworks!
pod 'OneSignalXCFramework', '>= 5.0.0', '< 6.0'
end
# Uncomment this line to define a global platform for your project
platform :ios, '11.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
project 'Runner', {
'Debug' => :debug,
'Profile' => :release,
'Release' => :release,
}
def flutter_root
generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
unless File.exist?(generated_xcode_build_settings_path)
raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
end
File.foreach(generated_xcode_build_settings_path) do |line|
matches = line.match(/FLUTTER_ROOT\=(.*)/)
return matches[1].strip if matches
end
raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
flutter_ios_podfile_setup
target 'Runner' do
use_frameworks!
use_modular_headers!
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
end
end
target 'OneSignalNotificationServiceExtension' do
use_frameworks!
pod 'OneSignalXCFramework', '>= 5.0.0', '< 6.0'
end
At the top of your Podfile
make sure you have platform :ios, '11.0'
.
- Or a newer iOS version if your app requires it.
# Uncomment this line to define a global platform for your project
platform :ios, '11.0'
Open terminal, cd
to the ios
directory, and run pod install
.
If you see the error below, add use_frameworks!
to the top of your podfile and try again.
- Runner (true) and OneSignalNotificationServiceExtension (false) do not both set use_frameworks!.
In the Xcode project navigator, select the OneSignalNotificationServiceExtension folder and open the NotificationService.m
or NotificationService.swift
file.
Replace the whole file's contents with the following code.
import UserNotifications
import OneSignalExtension
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var receivedRequest: UNNotificationRequest!
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.receivedRequest = request
self.contentHandler = contentHandler
self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let bestAttemptContent = bestAttemptContent {
/* DEBUGGING: Uncomment the 2 lines below to check this extension is executing
Note, this extension only runs when mutable-content is set
Setting an attachment or action buttons automatically adds this */
// print("Running NotificationServiceExtension")
// bestAttemptContent.body = "[Modified] " + bestAttemptContent.body
OneSignalExtension.didReceiveNotificationExtensionRequest(self.receivedRequest, with: bestAttemptContent, withContentHandler: self.contentHandler)
}
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
OneSignalExtension.serviceExtensionTimeWillExpireRequest(self.receivedRequest, with: self.bestAttemptContent)
contentHandler(bestAttemptContent)
}
}
}
#import <OneSignalExtension/OneSignalExtension.h>
#import "NotificationService.h"
@interface NotificationService ()
@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNNotificationRequest *receivedRequest;
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;
@end
@implementation NotificationService
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
self.receivedRequest = request;
self.contentHandler = contentHandler;
self.bestAttemptContent = [request.content mutableCopy];
/* DEBUGGING: Uncomment the 2 lines below and comment out the one above to ensure this extension is executing
Note, this extension only runs when mutable-content is set
Setting an attachment or action buttons automatically adds this */
// NSLog(@"Running NotificationServiceExtension");
// self.bestAttemptContent.body = [@"[Modified] " stringByAppendingString:self.bestAttemptContent.body];
[OneSignalExtension didReceiveNotificationExtensionRequest:self.receivedRequest
withMutableNotificationContent:self.bestAttemptContent
withContentHandler:self.contentHandler];
}
- (void)serviceExtensionTimeWillExpire {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
[OneSignalExtension serviceExtensionTimeWillExpireRequest:self.receivedRequest withMutableNotificationContent:self.bestAttemptContent];
self.contentHandler(self.bestAttemptContent);
}
@end
3. Android Setup
Verify the Android compileSdkVersion
is at least 33
for your project. Open your android/app/build.gradle
file and inspect the compileSdkVersion
property.
-
If
compileSdkVersion
in yourandroid/app/build.gradle
file is set toflutter.compileSdkVersion
, open yourandroid/local.properties
file and ensure a property offlutter.compileSdkVersion
is either non-existent or is set to a value of33
or higher. -
If
compileSdkVersion
in yourandroid/app/build.gradle
file is set to a number less than 33, update it to a value of33
or higher:
// ...
android {
compileSdkVersion 33
// ...
}
// ...
For more information about the Gradle build configuration in relation to Flutter, view the Flutter documentation.
Android Icons
By default, notifications will be shown with a small bell icon in the notification shade. Follow the Customize Notification Icons guide to create your own small and large notification icons for your app.
4. Initialization
You can now initialize OneSignal using the following code in your main.dart
file.
import 'package:onesignal_flutter/onesignal_flutter.dart';
//Remove this method to stop OneSignal Debugging
OneSignal.Debug.setLogLevel(OSLogLevel.verbose);
OneSignal.initialize("<YOUR APP ID HERE>");
// The promptForPushNotificationsWithUserResponse function will show the iOS or Android push notification prompt. We recommend removing the following code and instead using an In-App Message to prompt for notification permission
OneSignal.Notifications.requestPermission(true);
5. Testing
Run your app on a physical device to make sure it builds correctly.
If you used the provided code, then the requestPermission
method should prompt you to subscribe to push notifications. You can change this later.
Check your OneSignal Dashboard Audience > Subscriptions to see your User & Subscription Record.
Then head over to Messages > New Push to Send your first Push Notification from OneSignal.
Troubleshooting
If you run into any issues please see our Flutter troubleshooting guide.
Try the example project on our Github repository.
If stuck, contact support directly or email [email protected] for help.
For faster assistance, please provide:
- Your OneSignal App Id
- Details, logs, and/or screenshots of the issue
- Steps to reproduce
Recommended
Push permission with In-App Message
You can continue to opt-in users to push via the requestPermission
method. However, Apple's Human Interface Guidelines recommends that apps "Create an alert, modal view, or other interface that describes the types of information they want to send and gives people a clear way to opt in or out."
OneSignal provides In-App Messages to meet this recommendation and have a better user experience. This also permits you to ask for permission again in the future, since the native permission prompt is limited to how many times it can show and cannot be shown again if the user clicks deny.
See How to Prompt for Push Permissions with In-App Messages for details on implementing this.
Identify Users
Required if using integrations.
Recommended for messaging across multiple channels (push, email, sms).
OneSignal creates subscription-level records under a unique ID called the subscription_id
. A single user can have multiple subscription_id
records based on how many devices, email addresses, and phone numbers they use to interact with your app.
If your app has its own login system to track users, call login
at any time to link all channels to a single user. For more details, see Aliases & External ID.
var externalId = "123456789" // You will supply the external id to the OneSignal SDK
OneSignal.login(externalId);
Set Email and Phone Number
Recommended if using Email and SMS messaging.
Use the provided SDK methods to capture email and phone number when provided. Follow the channel quickstart guides for setup:
// Pass in email provided by customer
OneSignal.User.addEmail("[email protected]");
// Pass in phone number provided by customer
OneSignal.User.addSms("+11234567890");
Add Data Tags
Optional
Tags are custom key : value
pairs of String data used for tracking user events and properties. Setting tags is required for more complex segmentation and message personalization.
See Data Tags for more details.
OneSignal.User.addTagWithKey("test1", "val1");
Updated about 18 hours ago