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
Parameter | Data Type | Description |
---|---|---|
Debugging | ||
setLogLevel | Method | Enable logging to help debug OneSignal implementation |
Initialization | ||
init | Method | Starts initialization of OneSignal. See Flutter SDK Setup for details and code examples. |
inFocusDisplaying | Method | Setting to control how OneSignal notifications will be shown when one is received while your app is in focus. |
OSiOSSettings | Enum | iOS Represents different types of settings your application can use when initializing the SDK for iOS. |
Handling Notifications | ||
setNotificationReceivedHandler | Method | Adds 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. |
setNotificationOpenedHandler | Method | Adds an observer function/callback that will get executed whenever the user opens a push notification, or taps a button on a push notification. |
Privacy | ||
setRequiresUserPrivacyConsent | Method | Delays initialization of the SDK until the user provides privacy consent |
consentGranted | Method | Tells the SDK that the user has provided privacy consent (if required) |
iOS Prompting | ||
promptForPushNotificationsWithUserResponse | Method | Prompt 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 | ||
getPermissionSubscriptionState | Method | Get the current notification and permission state. Returns a OSPermissionSubscriptionState type. |
setPermissionObserver | Method | Adds an observer function/callback that will get executed whenever the Permission state changes (ie. user disables push notification permission) |
setSubscriptionObserver | Method | Adds 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) |
setSubscription | Method | Disable OneSignal from sending notifications to current device. |
External User IDs | ||
setExternalUserId | Method | Allows 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. |
removeExternalUserId | Method | Removes whatever was set as the current user's external user ID. |
Tagging | ||
getTags | Method | View Tags from current device record. |
sendTag | Method | Add a single Data Tag to current device record. |
sendTags | Method | Add multiple Data Tags to current device record. |
deleteTag | Method | Delete a Tag from current device record. |
deleteTags | Method | Delete multiple Tags from current device record. |
Location Data | ||
setLocationShared | Method | Disable or Enable SDK location collection. See Handling Personal Data. |
promptLocation | Method | Prompt Users for Location Not Recommended Recommended: Use In-App Message Location Opt-In Prompt. |
Sending Notifications | ||
postNotification | Method | Send or schedule a notification to a OneSignal Player ID. |
postNotificationWithJson | Method | |
In-App Messaging | ||
addTrigger | Method | Add a trigger, may show an In-App Message if its triggers conditions were met. |
addTriggers | Method | Add a map of triggers, may show an In-App Message if its triggers conditions were met. |
removeTriggerForKey | Method | Removes a list of triggers based on a collection of keys, may show an In-App Message if its triggers conditions were met. |
getTriggerValueForKey | Method | Gets a trigger value for a provided trigger key. |
pauseInAppMessages | Method | Allows you to temporarily pause all In App Messages. |
setInAppMessageClickHandler | Method | Sets an In App Message opened block |
setEmail | Method | Set 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. |
logoutEmail | Method | Log user out to dissociate email from device |
setEmailSubscriptionObserver | Method | Adds 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 | ||
OSNotificationOpenedResult | Class | Information returned from a notification the user received. |
OSNotification | Class | Represents a received push notification |
OSNotificationAction | Class | How user opened notification |
OSNotificationPayload | Class | Data that comes with a notification. |
### Enumerations | ||
OSNotificationDisplayType | Enum | Describes how notifications will be displayed. |
OSNotificationActionType | Enum | Describes the type of action a user took on a push noticiation (ie. tapping a button) |
OSNotificationPermission | Enum | iOS Describes the current user's notification permission status. |
OSCreateNotificationBadgeType | Enum | iOS Describes how badge logic is handled for a notification. |
OSCreateNotificationDelayOption | Enum | Describes the different options for how a notification can be delayed. |
Initialization
OSiOSSettings
OSiOSSettings
Enum
Describes different settings you can use when initializing iOS. Please note that these settings are ignored in Android.
Type | Description |
---|---|
autoPrompt | Describes a boolean property indicating if the SDK will automatically prompt the user for permission to send push notifications. |
inAppLaunchUrl | Describes 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. |
promptBeforeOpeningPushUrl | Describes 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. |
inFocusDisplayOption | Describes 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
setNotificationReceivedHandler
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
setNotificationOpenedHandler
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
postNotification
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
postNotificationWithJson
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
inFocusDisplayType
Gets setting on how notifications will be shown when the app is in focus.
OneSignal.shared.inFocusDisplayType;
External User ID's
setExternalUserId
setExternalUserId
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
removeExternalUserId
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
OSSubscriptionState
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.
Parameter | Type | Description |
---|---|---|
userSubscriptionSetting | Boolean | Indicates the current state of the setSubscription(bool) method. If you use this method to disable push notifications, this property will change to false . |
subscribed | Boolean | Indicates if the user is subscribed with OneSignal and can receive push notifications. |
userId | String | The current user's user identifier with OneSignal (also known as the playerId ). |
pushToken | String | The APNS (iOS) or GCM/FCM (android) push token. |
OSEmailSubscriptionState
OSEmailSubscriptionState
Represents the user's email subscription state with OneSignal.
Parameter | Type | Description |
---|---|---|
subscribed | Boolean | Indicates if the current user is subscribed with OneSignal for email, and can receive emails through OneSignal. |
emailUserId | String | The current user's identifier for email with OneSignal. |
emailAddress | String | The current user's email address set with OneSignal. |
OSPermissionState
OSPermissionState
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.
Parameter | Type | Description |
---|---|---|
hasPrompted | Boolean | Indicates if the user has been shown the Permission prompt to accept push notifications. |
provisional | Boolean | Indicates if the user is using iOS 12's new Provisional push notification authorization. |
status | OSNotificationPermission | Represents the current user's permission status (ie. authorized , notDetermined , etc.) |
OSSubscriptionStateChanges
OSSubscriptionStateChanges
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
.
Parameter | Type | Description |
---|---|---|
from | OSSubscriptionState | The previous push notification subscription state. |
to | OSSubscriptionState | The new/updated push notification subscription state. |
OSEmailSubscriptionStateChanges
OSEmailSubscriptionStateChanges
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.
Parameter | Type | Description |
---|---|---|
from | OSEmailSubscriptionState | The previous email subscription state. |
to | OSEmailSubscriptionState | The new/updated email subscription state. |
OSPermissionStateChanges
OSPermissionStateChanges
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
.
Parameter | Type | Description |
---|---|---|
from | OSPermissionState | The previous permission state. |
to | OSPermissionState | The new/updated permission state. |
OSNotification
OSNotification
This class represents a push notification that the user has received in your app from OneSignal.
Parameter | Type | Description |
---|---|---|
payload | OSNotificationPayload | Represents the payload of the push notification, such as the title, subtitle, buttons, and so on. |
displayType | OSNotificationDisplayType | Represents the display type your app was using when the notification was received, such as inAppAlert . |
shown | Boolean | Indicates if the user has seen the notification. |
appInFocus | Boolean | Indicates if the application was running (in focus) when the notification was received. |
silent | Boolean | Indicates if this notification was a silent notification. |
androidNotificationId | Integer | The Android notification ID for this push notification (android assigns each notification an individual ID, which is not the same as the OneSignal notificationId ) |
OSNotificationPayload
OSNotificationPayload
This class represents all of the various properties that control how a notification looks, such as the title, subtitle, etc.
Parameter | Type | Description |
---|---|---|
notificationId | String | The notification's OneSignal ID. |
templateId | String | If this notification was created from a Template on the OneSignal dashboard, this will be the ID of that template |
templateName | String | The name of the template (if any) that was used to create this push notification |
contentAvailable | Boolean | iOS Tells the system to launch your app in the background (ie. if content is available to download in the background) |
mutableContent | Boolean | iOS Tells the system to launch the Notification Extension Service |
category | String | iOS The category for this notification. This can trigger custom behavior (ie. if this notification should display a custom Content Extension for custom UI) |
badge | Integer | iOS If set, the SDK will set the application's badge count to be this value. |
badgeIncrement | Integer | iOS 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. |
subtitle | String | The subtitle of the notification. |
sound | String | The sound that should be played when the notification is received. |
title | String | The push notification's title. |
body | String | The body (main text) of the push notification. |
launchUrl | String | If set, the SDK will launch this URL when the notification is tapped. |
additionalData | Map<dynamic, dynamic> | This field contains custom data, you can set this to be whatever you want. |
attachments | Map<dynamic, dynamic> | iOS Contains any images, videos, etc. to be attached to the notification. |
buttons | List<OSActionButton> | An array of buttons to attach to the push notification. |
rawPayload | Map<dynamic, dynamic> | The actual notification JSON received by the SDK by the system. |
smallIcon | String | Android A URL or local resource name for an image to use as the notification's small icon. |
largeIcon | String | Android A URL or local resource name for an image to use as the notification's large icon. |
bigPicture | String | Android The URL or filename for the image to use as the big picture for the notification |
smallIconAccentColor | String | Android An ARGB hex value that controls the color of the small icon (which gets displayed on the status bar) |
ledColor | String | Android An ARGB hex color value that controls the color shown by the device's LED when the notification is received. |
lockScreenVisibility | Integer | Android 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) |
groupKey | String | Android All notifications with the same group key are grouped together. |
groupMessage | String | Android 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. |
collapseId | String | Android 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 |
fromProjectNumber | String | Android Tells you what project number/sender ID the notification was sent from |
priority | Integer | The 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
OSCreateNotification
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.
Parameter | Type | Description |
---|---|---|
playerIds | List | A list of OneSignal userId's (playerId's) that should receive this push notification. Must contain at least one player ID. |
content | String | The notification's content (body) |
languageCode | String | The two-character ISO 639-1 language code (ie. English = en) for this push notification. |
heading | String | The title/heading for this push notification. |
subtitle | String | The subtitle for this push notification. |
contentAvailable | Boolean | iOS Tells the system to launch the Notification Extension Service |
mutableContent | Boolean | iOS Tells the system to launch the Notification Extension Service |
additionalData | Map<dynamic, dynamic> | This field contains custom data, you can set this to be whatever you want. |
url | String | A URL that will be opened when a user taps on this push notification. |
iosAttachments | Map<String, String> | iOS A hash map containing all of the attachments (videos, images, etc) to be attached to this push notification. |
bigPicture | String | Android An image URL or resource name to use as the big picture for this push notification. |
buttons | List<OSActionButton > | A list of buttons to show on the push notification. |
iosCategory | String | iOSThe category identifier for iOS (controls various aspects of the notification, for example, whether to launch a Notification Content Extension) |
iosSound | String | iOS The sound file to play when the notification is received (ie. ping.aiff ) |
androidSound | String | Android The sound file to play when the notification is received (ie. ping.mp3 ) |
androidSmallIcon | String | Android An image URL or drawable local resource to use as the small icon for the notification. |
androidLargeIcon | String | Android An image URL or drawable local resource to use as the large icon for the notification. |
androidChannelId | String | The Android Oreo Notification Category to send the notification to. |
iosBadgeType | OSCreateNotificationBadgeType | iOS Indicates if the badge parameter will increase the existing badge type, or will override the existing badge type (setTo ) |
iosBadgeCount | Integer | iOS The amount to either set or increase the badge count by/to. |
collapseId | String | When a device receives multiple notifications that have the same collapseId , only the most recent notification will be shown. |
sendAfter | DateTime | Allows you to delay when a notification is sent. |
delayedOption | OSCreateNotificationDelayOption | Lets 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). |
deliveryTimeOfDay | String | If 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
OSNotificationOpenedResult
Describes the opening of a notification.
Parameter | Type | Description |
---|---|---|
notification | OSNotification | Represents a push notification received by your application from OneSignal. |
action | OSNotificationAction | If a user taps a button on a push notification, this property describes that action. |
OSNotificationAction
OSNotificationAction
Describes an action taken on a push notification (ie. tapping a button).
Parameter | Type | Description |
---|---|---|
type | OSNotiicationActionType | An 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). |
actionId | String | The ID of the button the user tapped (if any). Can be null. |
OSActionButton
OSActionButton
This class represents a button added to a push notification.
Parameter | Type | Description |
---|---|---|
id | String | The custom ID for this button. |
text | String | The title of the button shown to the user. |
icon | String | Android The icon to show on the button, either a URL or a local drawable resource name. |
OSAndroidBackgroundImageLayout
OSAndroidBackgroundImageLayout
This class represents the background image layout used for push notifications that show a background image.
Parameter | Type | Description |
---|---|---|
image | String | The image URL (or local drawable resource name) to show as the background image. |
titleTextColor | String | The ARGB hex color of the title. |
bodyTextColor | String | The ARGB hex color of the body text. |
Enumerations
OSNotificationDisplayType
OSNotificationDisplayType
Represents the different ways a notification can be displayed.
Type | Description |
---|---|
none | The SDK does not display the notification at all. This is useful if you want to create your own custom UI to display notifications. |
alert | Displays the notification as a popup alert. |
notification | Displays the notification as a normal system notification. |
OSNotificationActionType
OSNotificationActionType
Describes an action taken on a notification, such as tapping a button.
Type | Description |
---|---|
opened | The user tapped on the notification itself (not a button) |
actionTaken | The user tapped a button on the push notification. |
OSNotificationPermission
OSNotificationPermission
Describes the different types of permissions in regards to push notifications.
Type | Description |
---|---|
notDetermined | iOS The user has neither granted nor denied permission for your application to send push notifications. |
denied | The user has denied permission for your application to send push notifications. |
authorized | The user has granted permission for your application to send push notifications. |
provisional | iOS 12 beta Your app can send provisional/direct-to-history push notifications. |
OSCreateNotificationBadgeType
OSCreateNotificationBadgeType
Describes what happens when a push notification with a badge is received.
Type | Description |
---|---|
increase | Indicates 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. |
setTo | Indicates that the existing badge count will be overridden by the notification's new badge count. |
OSCreateNotificationDelayOption
OSCreateNotificationDelayOption
Describes the different ways to delay a notification.
Type | Description |
---|---|
timezone | This 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. |
lastActive | The same as Intelligent Delivery, the notification will be delivered based on when a user last opened your application. |
Updated almost 2 years ago