Flutter SDK 2.x.x

OneSignal Flutter SDK Reference.
Works with iOS and Android.

📘

Just Starting with Flutter?

Check out our Flutter SDK Setup Guide

ParameterData TypeDescription
Debugging
setLogLevelMethodEnable logging to help debug OneSignal implementation
Initialization
initMethodStarts initialization of OneSignal.
See Flutter SDK Setup for details and code examples.
inFocusDisplayingMethodSetting to control how OneSignal notifications will be shown when one is received while your app is in focus.
OSiOSSettingsEnumiOS Represents different types of settings your application can use when initializing the SDK for iOS.
Handling Notifications
setNotificationReceivedHandlerMethodAdds an observer function/callback that will get executed whenever a new OneSignal push notification is received on the device when app is in the foreground.
setNotificationOpenedHandlerMethodAdds an observer function/callback that will get executed whenever the user opens a push notification, or taps a button on a push notification.
Privacy
setRequiresUserPrivacyConsentMethodDelays initialization of the SDK until the user provides privacy consent
consentGrantedMethodTells the SDK that the user has provided privacy consent (if required)
iOS Prompting
promptForPushNotificationsWithUserResponseMethodPrompt the user for notification permissions. Callback fires as soon as the user accepts or declines notifications.

Must set kOSSettingsKeyAutoPrompt to false when calling initWithLaunchOptions.

Recommended: Set to false and follow iOS Push Opt-In Prompt.
User Status
getPermissionSubscriptionStateMethodGet the current notification and permission state. Returns a OSPermissionSubscriptionState type.
setPermissionObserverMethodAdds an observer function/callback that will get executed whenever the Permission state changes (ie. user disables push notification permission)
setSubscriptionObserverMethodAdds an observer function/callback that will get executed whenever the user's push notification subscription changes (ie. the user is assigned a OneSignal user ID)
setSubscriptionMethodDisable OneSignal from sending notifications to current device.
External User IDs
setExternalUserIdMethodAllows you to use your own system's user ID's to send push notifications to your users. To tie a user to a given user ID, you can use this method.
removeExternalUserIdMethodRemoves whatever was set as the current user's external user ID.
Tagging
getTagsMethodView Tags from current device record.
sendTagMethodAdd a single Data Tag to current device record.
sendTagsMethodAdd multiple Data Tags to current device record.
deleteTagMethodDelete a Tag from current device record.
deleteTagsMethodDelete multiple Tags from current device record.
Location Data
setLocationSharedMethodDisable or Enable SDK location collection. See Handling Personal Data.
promptLocationMethodPrompt Users for Location Not Recommended

Recommended: Use In-App Message Location Opt-In Prompt.
Sending Notifications
postNotificationMethodSend or schedule a notification to a OneSignal Player ID.
postNotificationWithJsonMethod
In-App Messaging
addTriggerMethodAdd a trigger, may show an In-App Message if its triggers conditions were met.
addTriggersMethodAdd a map of triggers, may show an In-App Message if its triggers conditions were met.
removeTriggerForKeyMethodRemoves a list of triggers based on a collection of keys, may show an In-App Message if its triggers conditions were met.
getTriggerValueForKeyMethodGets a trigger value for a provided trigger key.
pauseInAppMessagesMethodAllows you to temporarily pause all In App Messages.
setInAppMessageClickHandlerMethodSets an In App Message opened block
Email
setEmailMethodSet user's email. Creates a new user record for the email address. Use sendTag if you want to update a push user record with the email.
logoutEmailMethodLog user out to dissociate email from device
setEmailSubscriptionObserverMethodAdds an observer function/callback that will get executed whenever the user's OneSignal Email subscription changes (ie. OneSignal.setEmail is called and the user gets an email user ID)
Notification Objects
OSNotificationOpenedResultClassInformation returned from a notification the user received.
OSNotificationClassRepresents a received push notification
OSNotificationActionClassHow user opened notification
OSNotificationPayloadClassData that comes with a notification.
### Enumerations
OSNotificationDisplayTypeEnumDescribes how notifications will be displayed.
OSNotificationActionTypeEnumDescribes the type of action a user took on a push noticiation (ie. tapping a button)
OSNotificationPermissionEnumiOS Describes the current user's notification permission status.
OSCreateNotificationBadgeTypeEnumiOS Describes how badge logic is handled for a notification.
OSCreateNotificationDelayOptionEnumDescribes the different options for how a notification can be delayed.

Initialization

OSiOSSettings

Enum

Describes different settings you can use when initializing iOS. Please note that these settings are ignored in Android.

TypeDescription
autoPromptDescribes a boolean property indicating if the SDK will automatically prompt the user for permission to send push notifications.
inAppLaunchUrlDescribes a boolean property controlling if URL's are opened using an in-app web browser view, or if URL's open to safari. This applies to notifications with a launch URL that opens when the user taps a notification.
promptBeforeOpeningPushUrlDescribes a boolean property controlling if the SDK will present a prompt asking the user if they want to open a URL before the SDK opens it. If set to false, when a user taps a notification with a URL, the SDK will immediately open the URL without prompting for permission.
inFocusDisplayOptionDescribes an [OSNotificationDisplayType](#osnotificationdisplaytype] property that controls how notifications should be shown.

We recommend using setInFocusDisplayType() instead of using this iOS launch setting.

Handling Notifications

setNotificationReceivedHandler

Method

This function/callback will be called whenever your application receives a notification from OneSignal when the app is in the foreground.

OneSignal.shared.setNotificationReceivedHandler((OSNotification notification) {
  // a notification has been received
});

setNotificationOpenedHandler

Method

This function/callback will be called whenever a user taps on a OneSignal push notification from your application.

If your application was closed and the user taps a notification, the app will launch, and the SDK will call this handler.

OneSignal.shared.setNotificationOpenedHandler((OSNotificationOpenedResult result) {
  // a notification has been opened
});

postNotification

Method

Allows you to post a notification. To send a notification, you build a custom OSCreateNotification object with the various properties.

Please note that you must specify at least one OneSignal user ID that the notification should be sent to, using the playerIds property.

var status = await OneSignal.shared.getPermissionSubscriptionState();

var playerId = status.subscriptionStatus.userId;

await OneSignal.shared.postNotification(OSCreateNotification(
  playerIds: [playerId],
  content: "this is a test from OneSignal's Flutter SDK",
  heading: "Test Notification",
  buttons: [
    OSActionButton(text: "test1", id: "id1"),
    OSActionButton(text: "test2", id: "id2")
  ]
));

You can also send a silent notification (which will not alert the user in any way):

var status = await OneSignal.shared.getPermissionSubscriptionState();

var playerId = status.subscriptionStatus.userId;

await OneSignal.shared.postNotification(OSCreateNotification.silentNotification(
  playerIds: [playerId],
  additionalData: {
    'test' : 'value'
  }
));

postNotificationWithJson

Method

You can also manually build up notification JSON and send it with this method instead of using the OSCreateNotification class:

var status = await OneSignal.shared.getPermissionSubscriptionState();

var playerId = status.subscriptionStatus.userId;

var response = await OneSignal.shared.postNotificationWithJson({
  "include_player_ids" : [ playerId],
  "contents" : {"en" : "test notification"}
});

inFocusDisplayType

Property

Gets setting on how notifications will be shown when the app is in focus.

OneSignal.shared.inFocusDisplayType;

External User ID's

setExternalUserId

Method

If your system assigns unique identifiers to users, it can be annoying to have to also remember their OneSignal user ID's as well. To make things easier, OneSignal now allows you to set an external_id for your users. Simply call this method, pass in your custom user ID (as a string), and from now on when you send a push notification, you can use include_external_user_ids instead of include_player_ids.

var myCustomUniqueUserId = "something from my backend server";

OneSignal.shared.setExternalUserId(myCustomUniqueUserId);

removeExternalUserId

Method

If your user logs out of your app and you would like to disassociate their custom user ID from your system with their OneSignal user ID, you will want to call this method.

//usually called after the user logs out of your app
OneSignal.shared.removeExternalUserId()

Objects

OSSubscriptionState

Class

The subscription state contains information about the user's push notification subscription with OneSignal. For example, when the user first launches your app and gets registered with OneSignal, the subscription state will change. It contains properties such as the push token and OneSignal user ID.

ParameterTypeDescription
userSubscriptionSettingBooleanIndicates the current state of the setSubscription(bool) method. If you use this method to disable push notifications, this property will change to false.
subscribedBooleanIndicates if the user is subscribed with OneSignal and can receive push notifications.
userIdStringThe current user's user identifier with OneSignal (also known as the playerId).
pushTokenStringThe APNS (iOS) or GCM/FCM (android) push token.

OSEmailSubscriptionState

Class

Represents the user's email subscription state with OneSignal.

ParameterTypeDescription
subscribedBooleanIndicates if the current user is subscribed with OneSignal for email, and can receive emails through OneSignal.
emailUserIdStringThe current user's identifier for email with OneSignal.
emailAddressStringThe current user's email address set with OneSignal.

OSPermissionState

Class

Represents the permission state for push notifications. For example, in iOS, if the user taps 'Allow' on the push notification permission prompt, their OSPermissionState will change.

ParameterTypeDescription
hasPromptedBooleanIndicates if the user has been shown the Permission prompt to accept push notifications.
provisionalBooleanIndicates if the user is using iOS 12's new Provisional push notification authorization.
statusOSNotificationPermissionRepresents the current user's permission status (ie. authorized, notDetermined, etc.)

OSSubscriptionStateChanges

Class

Represents a change in the user's subscription state. For example, if the user first installs and opens your app, when they become registered with OneSignal, the subscription state will change to account for the new userId.

ParameterTypeDescription
fromOSSubscriptionStateThe previous push notification subscription state.
toOSSubscriptionStateThe new/updated push notification subscription state.

OSEmailSubscriptionStateChanges

Class

Represents a change in the user's email subscription state. For example, if your user enters their email address and your app calls setEmail(), the SDK will update OneSignal's server and will assign the user a new emailUserId. This will change the user's email subscription state.

ParameterTypeDescription
fromOSEmailSubscriptionStateThe previous email subscription state.
toOSEmailSubscriptionStateThe new/updated email subscription state.

OSPermissionStateChanges

Class

Represents a change in the user's email permission state. For example, if an iOS user taps Allow on the push notification permission prompt, the permission state will go from notDetermined to allowed.

ParameterTypeDescription
fromOSPermissionStateThe previous permission state.
toOSPermissionStateThe new/updated permission state.

OSNotification

Class

This class represents a push notification that the user has received in your app from OneSignal.

ParameterTypeDescription
payloadOSNotificationPayloadRepresents the payload of the push notification, such as the title, subtitle, buttons, and so on.
displayTypeOSNotificationDisplayTypeRepresents the display type your app was using when the notification was received, such as inAppAlert.
shownBooleanIndicates if the user has seen the notification.
appInFocusBooleanIndicates if the application was running (in focus) when the notification was received.
silentBooleanIndicates if this notification was a silent notification.
androidNotificationIdIntegerThe Android notification ID for this push notification (android assigns each notification an individual ID, which is not the same as the OneSignal notificationId)

OSNotificationPayload

Class

This class represents all of the various properties that control how a notification looks, such as the title, subtitle, etc.

ParameterTypeDescription
notificationIdStringThe notification's OneSignal ID.
templateIdStringIf this notification was created from a Template on the OneSignal dashboard, this will be the ID of that template
templateNameStringThe name of the template (if any) that was used to create this push notification
contentAvailableBooleaniOS Tells the system to launch your app in the background (ie. if content is available to download in the background)
mutableContentBooleaniOS Tells the system to launch the Notification Extension Service
categoryStringiOS The category for this notification. This can trigger custom behavior (ie. if this notification should display a custom Content Extension for custom UI)
badgeIntegeriOS If set, the SDK will set the application's badge count to be this value.
badgeIncrementIntegeriOS If set, the SDK will add this to the current badge's value. If you want to decrease (decrement) the badge count, set this to a negative value.
subtitleStringThe subtitle of the notification.
soundStringThe sound that should be played when the notification is received.
titleStringThe push notification's title.
bodyStringThe body (main text) of the push notification.
launchUrlStringIf set, the SDK will launch this URL when the notification is tapped.
additionalDataMap<dynamic, dynamic>This field contains custom data, you can set this to be whatever you want.
attachmentsMap<dynamic, dynamic>iOS Contains any images, videos, etc. to be attached to the notification.
buttonsList<OSActionButton>An array of buttons to attach to the push notification.
rawPayloadMap<dynamic, dynamic>The actual notification JSON received by the SDK by the system.
smallIconStringAndroid A URL or local resource name for an image to use as the notification's small icon.
largeIconStringAndroid A URL or local resource name for an image to use as the notification's large icon.
bigPictureStringAndroid The URL or filename for the image to use as the big picture for the notification
smallIconAccentColorStringAndroid An ARGB hex value that controls the color of the small icon (which gets displayed on the status bar)
ledColorStringAndroid An ARGB hex color value that controls the color shown by the device's LED when the notification is received.
lockScreenVisibilityIntegerAndroid API level 21+

Sets the visibility of the notification
1 = Public (default)
0 = Private (hidden from lock screen if user set 'Hide Sensitive content')
-1 = Secret (doesn't appear at all)
groupKeyStringAndroid All notifications with the same group key are grouped together.
groupMessageStringAndroid Android 6 and earlier

The message to display when multiple notifications have been stacked together. Note: Android 7+ allows groups (stacks) to be expanded, so this group message is no longer necessary.
collapseIdStringAndroid The collapse ID for the notification. As opposed to groupKey (which causes stacking), the collapse ID will completely replace any previously received push notifications that use the same collapse_id
fromProjectNumberStringAndroid Tells you what project number/sender ID the notification was sent from
priorityIntegerThe priority used with GCM/FCM to describe how urgent the notification is. A higher priority means the notification will be delivered faster. Default priority is 10.

OSCreateNotification

Class

This class represents a notification that will be created and sent by your application. Because the properties and format involved in creating a push notification are so different from the platform-dependent properties in receiving a notification (ie. from APNS or GCM), we have split this logic into it's own separate class.

ParameterTypeDescription
playerIdsListA list of OneSignal userId's (playerId's) that should receive this push notification. Must contain at least one player ID.
contentStringThe notification's content (body)
languageCodeStringThe two-character ISO 639-1 language code (ie. English = en) for this push notification.
headingStringThe title/heading for this push notification.
subtitleStringThe subtitle for this push notification.
contentAvailableBooleaniOS Tells the system to launch the Notification Extension Service
mutableContentBooleaniOS Tells the system to launch the Notification Extension Service
additionalDataMap<dynamic, dynamic>This field contains custom data, you can set this to be whatever you want.
urlStringA URL that will be opened when a user taps on this push notification.
iosAttachmentsMap<String, String>iOS A hash map containing all of the attachments (videos, images, etc) to be attached to this push notification.
bigPictureStringAndroid An image URL or resource name to use as the big picture for this push notification.
buttonsList<OSActionButton >A list of buttons to show on the push notification.
iosCategoryStringiOSThe category identifier for iOS (controls various aspects of the notification, for example, whether to launch a Notification Content Extension)
iosSoundStringiOS The sound file to play when the notification is received (ie. ping.aiff)
androidSoundStringAndroid The sound file to play when the notification is received (ie. ping.mp3)
androidSmallIconStringAndroid An image URL or drawable local resource to use as the small icon for the notification.
androidLargeIconStringAndroid An image URL or drawable local resource to use as the large icon for the notification.
androidChannelIdStringThe Android Oreo Notification Category to send the notification to.
iosBadgeTypeOSCreateNotificationBadgeTypeiOS Indicates if the badge parameter will increase the existing badge type, or will override the existing badge type (setTo)
iosBadgeCountIntegeriOS The amount to either set or increase the badge count by/to.
collapseIdStringWhen a device receives multiple notifications that have the same collapseId, only the most recent notification will be shown.
sendAfterDateTimeAllows you to delay when a notification is sent.
delayedOptionOSCreateNotificationDelayOptionLets you determine if a notification should be delayed by either lastActive (which means the notification will be sent at the same time the user last used your app), or timezone (which will use the time specified in deliveryTimeOfDay in the user's local timezone).
deliveryTimeOfDayStringIf the delayedOption is set to timezone, this property determines what time in the user's local timezone the notification should be sent at (ie. 9:00 AM)

OSNotificationOpenedResult

Class

Describes the opening of a notification.

ParameterTypeDescription
notificationOSNotificationRepresents a push notification received by your application from OneSignal.
actionOSNotificationActionIf a user taps a button on a push notification, this property describes that action.

OSNotificationAction

Class

Describes an action taken on a push notification (ie. tapping a button).

ParameterTypeDescription
typeOSNotiicationActionTypeAn enum that represents what type of action the user took when opening a push notification, such as action (tapping a button) or opened (tapping the push notification itself).
actionIdStringThe ID of the button the user tapped (if any). Can be null.

OSActionButton

Class

This class represents a button added to a push notification.

ParameterTypeDescription
idStringThe custom ID for this button.
textStringThe title of the button shown to the user.
iconStringAndroid The icon to show on the button, either a URL or a local drawable resource name.

OSAndroidBackgroundImageLayout

Class
,
Android

This class represents the background image layout used for push notifications that show a background image.

ParameterTypeDescription
imageStringThe image URL (or local drawable resource name) to show as the background image.
titleTextColorStringThe ARGB hex color of the title.
bodyTextColorStringThe ARGB hex color of the body text.

Enumerations

OSNotificationDisplayType

Enum

Represents the different ways a notification can be displayed.

TypeDescription
noneThe SDK does not display the notification at all. This is useful if you want to create your own custom UI to display notifications.
alertDisplays the notification as a popup alert.
notificationDisplays the notification as a normal system notification.

OSNotificationActionType

Enum

Describes an action taken on a notification, such as tapping a button.

TypeDescription
openedThe user tapped on the notification itself (not a button)
actionTakenThe user tapped a button on the push notification.

OSNotificationPermission

Enum

Describes the different types of permissions in regards to push notifications.

TypeDescription
notDeterminediOS The user has neither granted nor denied permission for your application to send push notifications.
deniedThe user has denied permission for your application to send push notifications.
authorizedThe user has granted permission for your application to send push notifications.
provisionaliOS 12 beta Your app can send provisional/direct-to-history push notifications.

OSCreateNotificationBadgeType

Enum

Describes what happens when a push notification with a badge is received.

TypeDescription
increaseIndicates that the badge value will increment the existing badge count for your application. If you want to decrement the badge count, use a negative number.
setToIndicates that the existing badge count will be overridden by the notification's new badge count.

OSCreateNotificationDelayOption

Enum

Describes the different ways to delay a notification.

TypeDescription
timezoneThis option will deliver a notification at the specified OSNotification deliveryTimeOfDay but in the user's local timezone. For example, if a user lives in the Pacific timezone and you send them a notification where notification.deliveryTimeOfDay is 9:00 AM, the notification will be delayed until it is 9:00AM PST.
lastActiveThe same as Intelligent Delivery, the notification will be delivered based on when a user last opened your application.