Hey! These docs are for version 7.0, which is no longer officially supported. Click here for the latest version, 9.0!

Flutter SDK Setup

Instructions for adding the OneSignal Flutter SDK to your Flutter app for iOS and Android

Step 1. Requirements

  • A OneSignal Account if you do not already have one
  • Your OneSignal App ID, available in Keys & IDs.
  • iOS - You MUST have a Mac with a new version of Xcode.

While setting up the Flutter SDK, you must generate the appropriate credentials for the platform(s) you are releasing on:

Running Example project

For your convenience, we've created an example project. You can run this project for iOS and Android.

  • git clone https://github.com/OneSignal/OneSignal-Flutter-SDK.git
  • cd OneSignal-Flutter-SDK/example
  • flutter run
  • flutter run -d {your device ID}

Step 2. Add the OneSignal Flutter SDK

2.1 To add the OneSignal Flutter SDK to your project, edit your project's pubspec.yaml file:

dependencies:
    onesignal_flutter: ^3.0.0

2.2 Run flutter packages get to install the SDK.

2.3 Now, in your Dart code, you can use:

import 'package:onesignal_flutter/onesignal_flutter.dart';

Step 3. Add an iOS Service Extension (iOS Apps Only)

The OneSignalNotificationServiceExtension allows your application (in iOS) to receive rich notifications with images and/or buttons, along with Badges and analytics.

3.1 Open your Xcode project.

3.2 Select File > New > Target

3.3 Select Notification Service Extension and press Next

730

3.4 Enter the product name as OneSignalNotificationServiceExtension and hit Next. Unless you are already using Swift in your project, we recommend that you use Objective-C as the language. Do not select "Activate" on the dialog shown after selecting "Finish".

730

3.5 Press Cancel on the Activate Scheme prompt

420

By canceling, you are keeping Xcode set to debug your app instead of the extension. If you selected Activate by accident, you can simply switch back to debug your app in Xcode (next to the Play button).

3.6 Open the Xcode project settings and select the OneSignalNotificationServiceExtension target. Unless you have a specific reason not to, you should set the Deployment Target to be iOS 10.

3100

3.7 Close the Xcode project. In the /ios directory of your project, open the Podfile and add the following to the bottom (just above any post_install logic):

target 'OneSignalNotificationServiceExtension' do
  pod 'OneSignalXCFramework', '>= 3.4.3', '< 4.0'
end

3.8 Open terminal, cd to the /ios directory, and run pod install.

If you see the error below, remove # from the above in front of use_frameworks! and try again.

- Runner (true) and OneSignalNotificationServiceExtension (false) do not both set use_frameworks!.

3.9 Open the newly created <project-name>.xcworkspace file.
Make sure to always open the workspace from now on.
In your project, in the OneSignalNotificationServiceExtension/ folder, open NotificationService.m and replace the whole file contents with:

#import <OneSignal/OneSignal.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];
    
    //If your SDK version is < 3.5.0 uncomment and use this code:
    /*
    [OneSignal didReceiveNotificationExtensionRequest:self.receivedRequest
                       withMutableNotificationContent:self.bestAttemptContent];
    self.contentHandler(self.bestAttemptContent);
    */
    
    /* DEBUGGING: Uncomment the 2 lines below and comment out the one above to ensure this extension is excuting
                  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];
    
    // Uncomment this line to set the default log level of NSE to VERBOSE so we get all logs from NSE logic
    //[OneSignal setLogLevel:ONE_S_LL_VERBOSE visualLevel:ONE_S_LL_NONE];
    [OneSignal 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.
    
    [OneSignal serviceExtensionTimeWillExpireRequest:self.receivedRequest withMutableNotificationContent:self.bestAttemptContent];
    
    self.contentHandler(self.bestAttemptContent);
}

@end
import UserNotifications

import OneSignal

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 {
            //If your SDK version is < 3.5.0 uncomment and use this code:
            /*
            OneSignal.didReceiveNotificationExtensionRequest(self.receivedRequest, with: self.bestAttemptContent)
            contentHandler(bestAttemptContent)
            */
            
            /* DEBUGGING: Uncomment the 2 lines below to check this extension is excuting
                          Note, this extension only runs when mutable-content is set
                          Setting an attachment or action buttons automatically adds this */
            //OneSignal.setLogLevel(.LL_VERBOSE, visualLevel: .LL_NONE)
            //bestAttemptContent.body = "[Modified] " + bestAttemptContent.body
            
            OneSignal.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 {
            OneSignal.serviceExtensionTimeWillExpireRequest(self.receivedRequest, with: self.bestAttemptContent)
            contentHandler(bestAttemptContent)
        }
    }
    
}

3.10 Finally, you will need to enable an App Group to use Confirmed Deliveries and increment/decrement Badges through push notifications.

Please follow the iOS SDK App Groups setup guide to add the OneSignal App Group in your app.

Step 4. Enable iOS Push Capability in Xcode (iOS Apps Only)

4.1 Select your project settings and under Capabilities, enable Push Notifications
4.2 Next, enable Background Modes and check Push Notifications

961

Step 5. Set up OneSignal for Android

Add the following to the very top (Line:1 ) of your android/app/build.gradle

buildscript {
    repositories {
        // ...
        maven { url 'https://plugins.gradle.org/m2/' } // Gradle Plugin Portal
    }
    dependencies {
        // ...
        // OneSignal-Gradle-Plugin
        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.10, 0.99.99]'
    }
}

apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'

Step 6 - Initialize the OneSignal SDK (All Platforms)

6.1 You can now initialize OneSignal using the following code in your main.dart file:

//Remove this method to stop OneSignal Debugging 
OneSignal.shared.setLogLevel(OSLogLevel.verbose, OSLogLevel.none);

OneSignal.shared.setAppId("YOUR_ONESIGNAL_APP_ID");

// The promptForPushNotificationsWithUserResponse function will show the iOS push notification prompt. We recommend removing the following code and instead using an In-App Message to prompt for notification permission
OneSignal.shared.promptUserForPushNotificationPermission().then((accepted) {
    print("Accepted permission: $accepted");
});

6.2 You can also add observers for various events, such as a new notification being received or opened, or observe changes to the subscription status:

OneSignal.shared.setNotificationWillShowInForegroundHandler((OSNotificationReceivedEvent event) {
  // Will be called whenever a notification is received in foreground
  // Display Notification, pass null param for not displaying the notification
        event.complete(event.notification);                                 
});

OneSignal.shared.setNotificationOpenedHandler((OSNotificationOpenedResult result) {
  // Will be called whenever a notification is opened/button pressed.
});

OneSignal.shared.setPermissionObserver((OSPermissionStateChanges changes) {
    // Will be called whenever the permission changes
    // (ie. user taps Allow on the permission prompt in iOS)
});

OneSignal.shared.setSubscriptionObserver((OSSubscriptionStateChanges changes) {
    // Will be called whenever the subscription changes 
    // (ie. user gets registered with OneSignal and gets a user ID)
});

OneSignal.shared.setEmailSubscriptionObserver((OSEmailSubscriptionStateChanges emailChanges) {
    // Will be called whenever then user's email subscription changes
    // (ie. OneSignal.setEmail(email) is called and the user gets registered
});

6.3 You can manually decide when to prompt the user for permission by calling promptUserForPushNotificationPermission:

OneSignal.shared.promptUserForPushNotificationPermission();

// If you want to know if the user allowed/denied permission,
// the function returns a Future<bool>:
bool allowed = await OneSignal.shared.promptUserForPushNotificationPermission();

Step 7. Run your app and send yourself a notification

Build and test your app to make sure your device is successfully subscribed to notifications and that you can receive notifications sent from the OneSignal dashboard.

📘

Problems/Errors?

If you are having trouble with our SDK, please see our troubleshooting guide

Step 8. Implement a Soft-Prompt In-App Message for iOS

Android devices are subscribed to notifications automatically when your app is installed, so this section only applies to your iOS release.

Apple's Human Interface Guidelines recommend 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 an easy option for a "soft-prompt" using 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 can no longer be shown in your app if the user clicks deny.

1200

See our iOS Push Opt-In Prompt for details on implementing this.

Step 9. Implement other OneSignal Features

  • Notification Delivery Settings - Learn about the many customizations and methods you can use to send notifications to your users in our Sending Push Messages guide.

  • Automated Messages - Set up Automated Messages to automatically re-engage app users who have lapsed or abandoned their cart. Learn more in our Automated Messages guide.

  • Segments and Tags - OneSignal supports simple and powerful tagging and segmentation to send messages to relevant users through our dashboard and API. Learn more in our Segments guide.

  • In-App Messages - OneSignal supports In-App Messaging in order to display rich content to your users or to present permission prompts, surveys, promotions, announcements, and more. Learn more in our In-App Messaging Overview.

  • E-Mail Support - OneSignal supports the delivery and automation of e-mail in addition to push notifications. Learn more in our Email Overview.

  • Flutter SDK API - Explore other methods available in our Flutter SDK API Documentation.

  • Remote API - Send notifications, import data, and export data using our simple and powerful API. Learn more in our OneSignal API overview..