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

Flutter SDK

OneSignal Flutter SDK. Works with iOS and Android.

📘

This reference covers version 3.0.0+ of the Flutter SDK

For the old reference, click here.

Coming from version 2? See full changes in version 3 in our Migration Guide.

📘

Just starting with Flutter?

Check out our Flutter SDK Setup guide.

ParameterData TypeDescription
Debugging
setLogLevelFunctionEnable logging to help debug OneSignal implementation.
Initialization
setAppId()Function* Required: Set the OneSignal app id.
Events, Handlers, & ObserversThe OneSignal SDK emits various "events" such as the receipt of a notification or a click event. You can use the following methods to attach and remove callbacks to these events.
setPermissionObserver()FunctionAdd a callback that fires when the native push permission changes.
setSubscriptionObserver()FunctionAdd a callback that fires when the OneSignal subscription state changes.
setEmailSubscriptionObserver()FunctionAdd a callback that fires when the OneSignal email subscription changes.
setNotificationWillShowInForegroundHandler()FunctionSet the callback to run just before displaying a notification while the app is in focus.
setInAppMessageClickHandler()FunctionSet the callback to run on in-app message click.
setNotificationOpenedHandler()FunctionSet the callback to run on notification open.
Privacy
setRequiresUserPrivacyConsentFunctionDelays initialization of the SDK until the user provides privacy consent
userProvidedPrivacyConsentFunctionWhether or not the user has provided privacy consent (if required)
consentGrantedFunctionIf your application is set to require the user's privacy consent, you can provide this consent using this method. Until you call consentGranted(true), the SDK will not fully initialize, and will not send any data to OneSignal.
requiresUserPrivacyConsentFunctionA boolean value indicating if the OneSignal SDK is waiting for the user's consent before it can initialize (if you set the app to
require the user's consent)
iOS Prompting
promptUserForPushNotificationPermissionFunctionPrompt 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 StatusMore Details
getDeviceState()FunctionGets information about the device.
disablePush()FunctionDisable the push notification subscription to OneSignal.
External IDs
setExternalUserIdFunctionAllows 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.
removeExternalUserIdFunctionRemoves whatever was set as the current user's external user ID.
Tagging
getTagsFunctionView Tags from current device record.
sendTagFunctionAdd a single Data Tag to current device record.
sendTagsFunctionAdd multiple Data Tags to current device record.
deleteTagFunctionDelete a Tag from current device record.
deleteTagsFunctionDelete multiple Tags from current device record.
Location Data
setLocationSharedFunctionDisable or Enable SDK location collection. See Handling Personal Data.
promptLocationFunctionPrompt Users for Location Not Recommended

Recommended: Use In-App Message Location Opt-In Prompt.
Sending Notifications
postNotificationFunctionSend or schedule a notification to a OneSignal Player ID.
clearNotificationFunctionAndroid Only Delete all app notifications
In-App Messaging
addTriggerFunctionAdd a trigger, may show an In-App Message if its triggers conditions were met.
addTriggersFunctionAdd a map of triggers, may show an In-App Message if its triggers conditions were met.
removeTriggerForKeyFunctionRemoves a list of triggers based on a collection of keys, may show an In-App Message if its triggers conditions were met.
getTriggerValueForKeyFunctionGets a trigger value for a provided trigger key.
pauseInAppMessagesFunctionAllows you to temporarily pause all In App Messages.
setInAppMessageClickHandlerFunctionSets an In App Message opened block
Outcomes
sendOutcomeFunctionIncreases the outcome count by 1 and will be counted each time sent.
sendUniqueOutcomeFunctionIncreases count by 1 only once. This can only be attributed to a single notification. If the method is called outside of an attribution window, it will be unattributed until a new session occurs.
sendOutcomeWithValueFunctionIncreases the count by 1 and the sum by the value. Will be counted each time sent.
Email
setEmailFunctionSet 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.
logoutEmailFunctionLog user out to dissociate email from device
Other
clearOneSignalNotificationsFunctionRemoves all OneSignal notifications from the Notification Shade.
removeNotificationFunctionThis function is used to remove a notification from the Android shade by supplying the Android notification identifier.
clearHandlersFunctionClears all handlers and observers.

Initialization

setAppId Function

To initialize, simply set the OneSignal application ID.

You can call setAppId at any point in your app's flow. This allows full initialization to be delayed until say, a user logs in.

OneSignal.shared.setAppId(appId);

Foreground Notification Control

You can specifically read notification data that will display while the app is in focus as well as change the display type dynamically. This allows developers to have even greater control over the notification experience.

Replaces inFocusDisplaying() functionality.

setNotificationWillShowInForegroundHandler Function

Runs before displaying a notification while the app is in focus. Use this handler to decide if the notification should show or not.

Note: this runs after the Notification Service Extension which can be used to modify the notification before showing it (native code).

The callback argument is a notification received event object.

OneSignal.shared.setNotificationWillShowInForegroundHandler(notifReceivedEvent => {
    console.log("OneSignal: notification will show in foreground:", notifReceivedEvent);
    let notif = notifReceivedEvent.getNotification();
    setTimeout(() => notifReceivedEvent.complete(notif), 0);
});

The callback argument object has two functions:

FieldDescription
getNotification()Retrieves the notification object.

This returned object is of class (OSNotification).
complete()Show Notification:
Pass the notification to this function in order to display it while the app is in the foreground.

Silence Notification:
If you would like to silence the notification, call complete() with no argument.

Handlers

setInAppMessageClickHandler Function

Set the callback to run on an In-App Message click.

OneSignal.shared.setInAppMessageClickHandler(event => {
    console.log("OneSignal IAM clicked:", event);
});

Click event parameters:

ParameterDescription
click_nameAn optional click name entered defined by the app developer when creating the IAM.
click_url An optional URL that opens when the action takes place.
closes_message Whether tapping on the element closed the In-App Message.
first_click Whether this was the first action taken on the in app message.
outcomes Outcome for action.

Mainly useful for debugging
prompts Permission prompts.

Mainly useful for debugging
tags Tags for action.

Mainly useful for debugging
url_target Determines where the URL is opened, ie.

Mainly useful for debugging

setNotificationOpenedHandler Function

Set the callback to run on notification open/click.

OneSignal.shared.setNotificationOpenedHandler(openedEvent => {
    console.log("OneSignal: notification opened:", openedEvent);
  const { action, notification } = openedEvent;
});

Opened event parameters:

ParameterDescription
actionThe action the user took on the notification.

Parameter:
type:
0) notification was clicked
1) button was clicked
notificationThe notification the user received.

Of class OSNotification

Observers

Each callback you pass to an observer adder function will receive a state change object when fired that contains two parameters: to and from. The parameters on those objects are the same between the two. This format allows for the detection of the previous state and the new state.

Example: a change in the subscription state of the device might see the isSubscribed parameter change from false to true. You can detect the change by the event.from.isSubscribed and event.to.isSubscribed objects.

Important: as designated by the "add" prefix to these functions, it is possible to add multiple callbacks to the same event. The callbacks will then fire independently when the event occurs. (Related: see clearHandlers function).

setPermissionObserver Function

Add a callback that fires when the native push permission changes.

Change event parameters:

ParameterDescription
areNotificationsEnabled (Android)Whether the device-level permission is granted or denied (boolean).
hasPrompted (iOS)Did the user answer the notification permission prompt.
provisional (iOS)Is provisional push authorization enabled.
status (iOS)0 - "NotDetermined"
1 - "Denied"
2 - "Authorized"
3 - "Provisional"
4 - "Ephemeral"

setSubscriptionObserver Function

Add a callback that fires when the OneSignal subscription state changes.

Change event parameters:

ParameterDescription
userIdThe OneSignal player identifier.
pushTokenThe native push token identifier used by FCM / HMS / FireOS / APNs.
isPushDisabledIs push disabled (disablePush was called).
isSubscribed (Android)Whether the player is subscribed to OneSignal.

setEmailSubscriptionObserver Function

Add a callback that fires when the OneSignal email subscription changes.

Change event parameters:

ParameterDescription
emailAddressThe email address associated with this player record.
emailUserIdThe UUID associated with the email record.
isSubscribedWhether the associated email record is subscribed to OneSignal messaging.

Example

OneSignal.shared.setPermissionObserver((OSPermissionStateChanges changes) {
    console.log("OneSignal: permission changed:", event);
});

OneSignal.shared.setSubscriptionObserver((OSSubscriptionStateChanges changes) {
    console.log("OneSignal: subscription changed:", event);
});

OneSignal.shared.setEmailSubscriptionObserver((OSEmailSubscriptionStateChanges changes) {
    console.log("OneSignal: email subscription changed: ", event);
});

Other Functions

getDeviceState Function

ASYNC
Returns an OSDeviceState object with device info.

🚧

Do not cache OSDeviceState object

This method returns a "snapshot" of the device state for when it was called. Make sure to call getDeviceState again to get the latest state.

OneSignal.shared.getDeviceState().then((deviceState) {
      print("DeviceState: ${deviceState?.jsonRepresentation()}");
});

deviceState parameters:

TypeDescription
isSubscribedGet whether the device is subscribed to receive OneSignal push notifications.
isPushDisabledWas push disabled with disablePush.
userIdGet the OneSignal user (player) id
pushTokenGet device's push token.
This can be one of the following depending on the device:
- Google FCM token
- Huawei HMS token
- FireOS token
emailUserIdGet the OneSignal user email id.
Only available if OneSignal.setEmail() was called.
emailAddressGet the user email address.
Only available if OneSignal.setEmail() was called.
isEmailSubscribedIs there an associated email record that is subscribed to OneSignal messaging.
hasNotificationPermissioniOS Only

Whether notifications are enabled on the device at the app level.
notificationPermissionStatusiOS Only

0 = NotDetermined
1 = Denied
2 = Authorized
3 = Provisional
4 = Ephemeral

disablePush Function

Use this function to opt users out of receiving all notifications through OneSignal.

OneSignal.shared.disablePush(true);

clearHandlers Function

Clears all handlers and observers.

📘

While this function clears both handlers AND observers, it is mainly useful for the observers since multiple observers can be added to a single event. React Native hot-reloading can lead to the buildup of these observers while in the dev environment which will result in multiple firings of the given callbacks. To avoid this, call in componentWillUnmount().


OSNotification

NameDescription
OSNotificationContains all notification properties such as title, body, additionalData, etc...

OSNotification Object

In version 4, the OSNotification class is composed of all notification properties in a single object. This is the object passed into the notificationWillShowInForeground handler.

ParameterDescription
additionalDataCustom additional data that was sent with the notification. Set on the dashboard under Options > Additional Data or with the data field on the REST API.
notificationIdThe OneSignal notification UUID.
bodyThe body text of the notification.
titleThe title text of the notification.
launchUrlThe URL opened when opening the notification.
actionButtonsThe list of action buttons on the notification.
soundThe sound resource played when the notification is shown.
rawPayloadThe raw JSON payload string received from OneSignal.
largeIcon (Android)The large icon set on the notification.
bigPicture (Android)The big picture image set on the notification.
smallIcon (Android)The small icon resource name set on the notification.
smallIconAccentColor (Android)The accent color shown around small notification icon on Android 5+ devices. ARGB format.
ledColor (Android)LED string. Devices that have a notification LED will blink in this color. ARGB format.
collapseId (Android)The collapse id for the notification.
priority (Android)The priority of the notification. Values range from -2 to 2 (see Android's NotificationCompat reference for more info.
fromProjectNumber (Android)The Google project number the notification was sent under.
groupKey (Android)Notifications with this same key will be grouped together as a single summary notification.
groupMessage (Android)The summary text displayed in the summary notification.
lockScreenVisibility (Android)Privacy setting for how the notification should be shown on the lockscreen of Android 5+ devices.

1 (Default) - Public (fully visible)
0 - Private (Contents are hidden)
-1 - Secret (not shown).
badge (iOS)The badge number assigned to the application icon.
category (iOS)Notification category key previously registered to display with.
threadId (iOS)iOS 10+ only. Groups notifications into threads.
subtitle (iOS)The message subtitle.
attachments (iOS)iOS 10+ only. Attachments sent as part of the rich notification.
templateId (iOS)Unique Template Identifier.
templateName (iOS)Name of Template.
mutableContent (iOS)True when the key mutable-content is set to 1 in the APNS payload.

See Apple's documentation for more details.
badgeIncrement (iOS)The amount to increment the badge icon number.
contentAvailable (iOS)True when the key content-available is set to 1 in the APNS payload. Used to wake your app when the payload is received.

See Apple's documentation for more details.

Privacy

userProvidedPrivacyConsent Function

Whether the user has provided privacy consent (if required).

Clear Notifications (Android Only)

clearOneSignalNotifications Function

Removes all OneSignal notifications from the Notification Shade.

// Calling clearOneSignalNotifications
OneSignal.shared.clearOneSignalNotifications();

Remove Notifications (Android Only)

removeNotification Function

This function is used to remove a notification from the Android shade by supplying the Android notification identifier. The notification identifier can be found as part of the OSNotification object.

// Calling removeNotification
OneSignal.shared.removeNotification(id);

Troubleshooting

Troubleshooting the Flutter SDK