Skip to content

Flutter

Integration

Kumulos provides an SDK in the form of a Dart package to ease the integration of the Kumulos Analytics, Push Notification, Crash Reporting and Build features into your Flutter apps.

Installation

Add the following dependency to your pubspec.yaml and run pub install:

dependencies:
  kumulos_sdk_flutter: 1.2.0

Android Project Setup (required)

Add the following to your android/app/build.gradle file:

android {
    // ...

    packagingOptions {
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/ASL2.0'
        exclude 'META-INF/LICENSE'
    }
}

Initialization

Create a kumulos.json file in your project's root directory with Kumulos configuration:

{
    "apiKey": "YOUR_API_KEY",
    "secretKey": "YOUR_SECRET_KEY",
    "enableCrashReporting": false, // false, true
    "inAppConsentStrategy": "in-app-disabled", // in-app-disabled, auto-enroll, explicit-by-user
    "enableDeferredDeepLinking": false // false, true, or string of CNAME URL to use
}

Your API Key and Secret Key can be obtained from the App Dashboard in your agency console.

Declare the asset in your pubspec.yaml:

assets:
  - kumulos.json

Checking installs of your App

When you run your app on a simulator or install your app on a device, you can check that the SDK has been initialized correctly by selecting the app and clicking the Installs tab to see the ten most recent installs of your app. Click on any install to see more information.

Recent installs

If you experience any difficulties integrating an SDK or initializing the Kumulos client, please don't hesitate to contact support who are standing by to help!

That's it, you're now good to go! Continue reading to learn more about analytics, configuring push notifications and calling Build API methods in your app.

Installation ID

When initialized for the first time, the Kumulos SDK will create a unique identifier for the current installation. This identifier can be used to target push notifications to a specific device via KScript or the Push Notifications API.

In order to retrieve this identifier, simply access the class variable:

var id = await Kumulos.installId;

Once you have the installation ID, you can send it to your app's backend to be used later for push targeting. For more information about push targeting, please see the KScript Documentation or push notification documentation as appropriate.

Analytics

Kumulos provides concise and easy to consume analytics & reporting features. By initializing the SDK, you automatically get session & engagement reporting out the box.

Session Analytics

Kumulos records sessions based on application foreground and background events. When an app enters the background, Kumulos will wait for a configurable idle period. If there are no more foreground events during that idle period, the current session will be closed.

Session analytics

So long as you initialize the SDK at some point in your app's lifecycle, Kumulos will automatically record analytics data such as the device model, operating system version and more, available in Analytics & Reporting for your app.

Event Tracking

Kumulos allows you to track custom analytics events that can be used as a trigger to fire automation rules (e.g. to trigger a push notification) or as steps in a funnel to track conversion through key user journeys in your app.

Track conversion

To track a custom analytics event, use Kumulos.trackEvent as follows:

Kumulos.trackEvent(eventType: 'product.purchased', properties: {
    'productId': 404
});

Each event and its properties must be less than 250 KiB in size for the event to be tracked.

Event tracking is available offline as all events are persisted locally before being synced to the server in batches in the background.

A similar method trackEventImmediately will immediately start an event sync rather than waiting for the next time the app is backgrounded.

Checking events from your App

When you run your app on a simulator or install your app on a device, you can check that the SDK is recording events correctly by selecting the app and clicking the Installs tab to see the ten most recent installs of your app. Click on any install and then click on the Events tab.

Install events

Alternatively, to see counts of all analytics events, including system events such as opened a push notification, recorded by installs of the app in the last 30 days, expand 'Analytics' and click 'Explore' in the left menu. For comparison, the total number of sessions in the same period is shown.

Analytics Explorer

User Association

Kumulos allows associating a user identifier with the current installation ID. This user identifier is useful for performing analytics aggregations & analyses at the user level, for example, funnels completed by users across multiple devices. You can also optionally associate a collection of attributes with the user.

To associate the current app installation with a user, you can use the helper method as shown below:

Kumulos.associateUserWithInstall(identifier: 'unique-user-id');

User association is time-aware, so say two different users log in to the app, their user IDs will be associated with the same install for the time between subsequent calls to the helper method. For example:

Kumulos.associateUserWithInstall(identifier: 'Bob');
// This event will belong to Bob
Kumulos.trackEvent(eventType: 'product.purchased');
Kumulos.associateUserWithInstall(identifier: 'Alice');
// This event will belong to Alice
Kumulos.trackEvent(eventType: 'product.purchased');

Attributes

You can optionally associate a collection of attributes with the user for targeting, personalization or attribution. To associate attributes with the user, pass a collection into the helper method as shown.

var attributes = {
    'name': 'Shawn',
    'age': 25
};

Kumulos.associateUserWithInstall(identifier: 'unique-user-id', attributes: attributes);

The collection of attributes for a given user must be less than 250 KiB in size.

If you do not have a user identifier, use the installation ID generated by the Kumulos SDK.

Location Tracking

You can send Kumulos location updates and use this to trigger events such as push notifications when an install enters a GeoFence.

Once you have configured location updates on the platform of choice you can send the updates to Kumulos via the helper method in the stats namespace.

Kumulos.sendLocationUpdate(latitude: -54.618946, longitude: -65.234551);

For information on receiving location updates, see the Flutter Location library.

Beacons

You can send Kumulos beacon proximity updates and use these to trigger automations such as sending a push notification when an install is in proximity to a beacon.

The Kumulos SDK provides helper methods to notify our services of proximity to a detected beacon.

You will need to integrate a suitable plugin to detect the beacon proximity events (for example, flutter_beacon).

Eddystone Beacon Detection

Kumulos.sendEddystoneBeaconProximity(
    hexNamespace: 'namespace',
    hexInstance: 'instance',
    distanceMetres: 10
);

Beacon monitoring on Android typically requires a device with BLE, and API level 18+. You can read more about detecting beacons in the Android Nearby reference.

iBeacon Detection

Kumulos.sendiBeaconProximity({
    proximityUuid: 'vendor-uuid',
    major: 1,
    minor: 2
});

Messaging & Push Notifications

Kumulos provides powerful multi-channel messaging services to reach your users. By initializing the SDK you can quickly and easily receive both push notifications to re-engage your users as well as feature-rich In-App messages.

Configuration & Integration

The Kumulos SDK provides all functionality to handle push registration & notifications using FCM and APNS.

To fully integrate this, there are some steps required for each platform before you can consume pushes from the JS layer. The steps required for each platform are documented below.

Configuring APNS for iOS

The video below shows how to create a push certificate on your Apple Developer portal, configure these certificates in Kumulos, and how to then configure the necessary entitlements in your iOS Xcode project.

Configuring APNS for iOS with Kumulos

The key points are:

  • Create an iOS push notifications certificate for your bundle ID
  • Upload the generated certificates from Apple to Kumulos
  • Enable the Push Notifications capability in your Xcode project
  • Enable the Remote Notifications Background Mode in your Xcode project

Once completed, you are ready to request the push token from the user and test.

Note you must use a real device to test push notifications on iOS because simulators cannot register for push notifications.

Configuring FCM for Android

The video below shows how to create a Firebase project configuration to make use of FCM to send push notifications to Android devices.

Enabling Push Notifications for Android

The key points are:

  • Create a Firebase project for FCM
  • Upload FCM credentials to Kumulos via the your-project-firebase-adminsdk.json file
  • Download the google-services.json and add to your project's android/app/ directory
  • Add classpath 'com.google.gms:google-services:4.2.0' to your android/build.gradle buildscript dependencies section
  • Add the FCM library dependency to your android/app/build.gradle file
  • Add apply plugin: 'com.google.gms.google-services' at the bottom of your android/app/build.gradle file
// android/app/build.gradle
...
dependencies {
    // Add firebase-messaging dep using BoM to get compatible version
    // of Android FCM push gateway library for Kumulos to retrieve
    // FCM push tokens.
    implementation platform('com.google.firebase:firebase-bom:28.2.0')
    implementation 'com.google.firebase:firebase-messaging'
}

apply plugin: 'com.google.gms.google-services'

Please note it is the Google Service Account private key JSON file that needs to be uploaded to Kumulos, not the Google Services JSON file you include in your app project. The Google Service Account JSON file can be generated from the 'Service Accounts' section of the Firebase Developer console as is shown in the relevant section of the video above.

After this setup has been completed, you can continue with the client registration.

Enabling In-App Messaging

In your kumulos.json configuration, change the inAppConsentStrategy value as follows:

{
    "apiKey": "YOUR_API_KEY",
    "secretKey": "YOUR_SECRET_KEY",
    "enableCrashReporting": false,
    "inAppConsentStrategy": "auto-enroll", // in-app-disabled, auto-enroll, explicit-by-user
    "enableDeferredDeepLinking": false
}

The above configurations set up auto-enrollment for in-app messaging where the SDK will automatically enable in-app messaging for the app user. The other supported strategy explicit-by-user is discussed in a later section.

Registering for & Handling Push Notifications

The following sample code shows how to use Kumulos to handle push notifications for deep-linking and other common messaging tasks.

import 'package:kumulos_sdk_flutter/main.dart';

Kumulos.setEventHandlers({
    pushReceivedHandler: (notification) => {
        // Called when a push is received with your app in the foreground
    },
    pushOpenedHandler: (notification) => {
        // Called when a user taps on a push notification
    },
    inAppDeepLinkHandler: (data) => {
        // Called when a user taps a deep-link action button from an in-app message
    }
});

// When you are ready to request the push token from the user, you would then call:
Kumulos.pushRequestToken();

If you want to unregister the token for the current installation, you can use Kumulos.pushUnregister().

Checking Push Registrations

When you run your app on a simulator or install your app on a device, you can check that the install has successfully registered for push notifications by selecting the app and clicking the Installs tab to see the ten most recent installs of your app.

Click on an install, click the 'Push' tab and click Send Test Push.

Install push details

If you do not receive the push notification, check the Error Log for any errors sending the push notification to the native push gateways. If you continue to experience problems, please don't hesitate to contact support who are standing by to help!

Supporting Pictures and Action Buttons in Notifications

When sending a push notification you can attach a picture or action buttons to it. They will show on iOS 10+ devices and Android devices with API level 16+.

Integrating Android

No extra steps needed.

Integrating iOS

The notification will expand upon swiping the notification on devices supporting 3D Touch. In order to enable this functionality you need open your iOS project in Xcode and add a Notification Service Extension to your application.

Make sure to correctly set up signing for the extension target.

Add the following to the ios/Podfile generated by Flutter and run pod install.

target 'KumulosNotificationServiceExtension' do
  pod 'KumulosSdkObjectiveCExtension', '4.5.2'
end

Then replace the contents of NotificationService.m with the following lines:

#import "NotificationService.h"
#import <KumulosSDKExtension/KumulosNotificationService.h>

@interface NotificationService ()
@end

@implementation NotificationService
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
   [KumulosNotificationService didReceiveNotificationRequest:request withContentHandler: contentHandler];
}
@end

Advanced

Supporting push delivery tracking and badges

For push delivery tracking and badges to work correctly you need to

  1. Set up Notification Service Extension as described above
  2. Add App Groups capability to both your App and Notification Service Extension targets
  3. Set group to group.{your.bundle.identifier}.kumulos for both targets

Note that due to iOS limitations badge is not set when app is in the foreground

Handling notification action buttons

When a user interacts with your push message the pushOpenedHandler defined as above is called. If a button was tapped, the notification object will contain an actionId property:

import 'dart:developer' as developer;

Kumulos.setEventHandlers({
    ...
    pushOpenedHandler: (notification) => {
        developer.log(notification.actionId);
    },
});

If you would like your users to opt-in to receive In-App messages you can configure the SDK during initialization to make opt-in explicit by setting the strategy, then calling the SDK helper to manage their consent.

In your kumulos.json configuration file, change the inAppConsentStrategy value to explicit-by-user:

{
    "apiKey": "YOUR_API_KEY",
    "secretKey": "YOUR_SECRET_KEY",
    "enableCrashReporting": false,
    "inAppConsentStrategy": "explicit-by-user", // in-app-disabled, auto-enroll, explicit-by-user
    "enableDeferredDeepLinking": false
}

Once the config has been set, you can now manage consent from your Dart code:

KumulosInApp.updateConsentForUser(true);

Note managing consent explicitly with the AUTO_ENROLL strategy is not supported and will result in a runtime exception

Deep-linking for In-App

In-App messages allow you to hand-off to Flutter application screens via deep-linking action buttons. When tapped, these buttons pass control to the defined deep-link handler, including their defined data payload (configured in the In-App message composer for the action button).

Kumulos.setEventHandlers({
    ...,
    inAppDeepLinkHandler: (data) => {
        // Called when a user taps a deep-link action button from an in-app message
    }
});

Using the In-App Inbox

In-app messages can optionally be persisted in a user-level inbox for later retrieval. This allows you to build features such as loyalty rewards or expiring coupons into your app. Regardless of whether they are stored in the inbox, the maximum amount of in-apps stored on a device is 50 (the oldest messages exceeding this limit will be evicted).

Retrieve messages

To retrieve a list of messages from the user's inbox and present the first in the list, see the following example:

var items = await KumulosInApp.getInboxItems();
var presentationResult = await KumulosInApp.presentInboxMessage(items[0]);
Mark as read

To mark a single or all inbox messages as read:

//single
var items = await KumulosInApp.getInboxItems();
var presentationResult = await KumulosInApp.markAsRead(items[0]);

//all
KumulosInApp.markAllInboxItemsAsRead();
Delete message

You can also delete an in-app message from inbox:

var items = await KumulosInApp.getInboxItems();
var deleted = await KumulosInApp.deleteMessageFromInbox(items[0]);
Inbox updated handler

In order to be notified when inbox changes you may set up a handler. The handler fires when one of the following happens to an in-app with an inbox configuration:

  • message fetched from server
  • message opened
  • message marked as read
  • message deleted
  • message evicted (expires or limit of stored messages exceeded)

You can use it as follows:

KumulosInApp.setOnInboxUpdatedHandler(() {
  // refresh your inbox
});

Note, you should set the handler after Kumulos has been initialized.

Note, you can do KumulosInApp.setOnInboxUpdatedHandler(null) when you stop being interested in inbox updates.

Get inbox summary

You can retrieve an inbox summary as follows:

var summary = await KumulosInApp.getInboxSummary();
// Use the summary counts

Channels

You can create and manage subscriptions to push channels from the SDK. Channels allow you to send push notifications to certain interest groups.

All channel management is performed through methods of the PushChannelManager class.

var subManager = await Kumulos.pushChannelManager;

The interface of the subscription manager is as follows:

class KumulosChannel {
  final String uuid;
  final String? name;
  final bool isSubscribed;
  final Map<String, dynamic>? meta;
}

class PushChannelManager {
    constructor(client: KumulosClient);
    /**
     * Subscribes to the channels given by unique ID
     */
    Future<void> subscribe(List<String> uuids);
    /**
     * Unsubscribes from the channels given by unique ID
     */
    Future<void> unsubscribe(List<String> uuids);
    /**
     * Sets the current installations channel subscriptions to those given by unique ID.
     *
     * Any other subscriptions will be removed.
     */
    Future<void> setSubscriptions(List<String> uuids);
    /**
     * Clears all of the existing installation's channel subscriptions
     */
    Future<void> clearSubscriptions();
    /**
     * Lists the channels available to this installation along with subscription status
     */
    Future<List<KumulosChannel>> listChannels();
    /**
     * Creates a push channel and optionally subscribes the current installation.
     *
     * Name is optional, but required if showInPortal is true.
     */
    Future<KumulosChannel> createChannel(
      {required String uuid,
      bool subscribe = false,
      String? name,
      bool showInPortal = false,
      Map<String, dynamic>? meta});
}

When creating channels, the visibility and meta data can be controlled. Please make sure you understand these concepts when creating channels from the SDK.

Deferred Deep Linking

Deep linking allows users to reach app content by clicking a link. This can be achieved even if app is not installed.

To integrate deep linking into your Flutter project, you have to complete the following steps.

Configuration & Setup (Dart)

Configure a deep link handler:

import 'package:kumulos_sdk_flutter/main.dart';

Kumulos.setEventHandlers({
    ...
    deepLinkHandler: (outcome) {
      switch (outcome.resolution) {
        case KumulosDeepLinkResolution.LinkMatched:
          // Inspect the outcome.linkData and navigate the user
          // to the deep link content
          break;
        default:
          // Handle generic non-match case
          break;
      }
    }
});

Configuration & Setup (iOS)

You need to associate a domain with your app. Note that the subdomain you specify here should match the one you specified on the deep link configuration page on Kumulos Dashboard.

  1. Add the Associated Domains capability to your main app target
  2. Set 'domains' to applinks:{yourSubdomain}.lnk.click

Associated Domain capability

Configuration & Setup (Android)

Add an intent filter to your main activity in the AndroidManifest.xml:

<intent-filter android:label="deepLabel" android:autoVerify="true">
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <!-- Specify which URIs should be matched. Note, domain should be .lnk.click -->
    <data android:scheme="https" android:host="subdomain.lnk.click"/>
</intent-filter>

Note that the subdomain you specify above should match the one you specified on the deep link configuration page on the Kumulos Dashboard.

Note that setting android:autoVerify="true" will verify ownership of the domain, so, instead of offering a list of apps to select from your app will open automatically. No further actions are needed to enable this.

Add following overrides to the `MainActivity.java``:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Kumulos.seeIntent(this, getIntent(), savedInstanceState);
}

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    Kumulos.seeInputFocus(this, hasFocus);
}

@Override
protected void onNewIntent(Intent intent) {
   super.onNewIntent(intent);
   Kumulos.seeIntent(this, intent);
}

Build

You can call API methods defined in the Kumulos Build service using the KumulosBackendClient.

To talk to Kumulos, you need two things:

  • your method title (in lowerCamelCase)
  • an (optional) parameters object

See example usage of the client below:

var client = await Kumulos.backendRpcClient;
var result = await client.call(
    methodAlias: 'getUserProfileExample',
    params: {'username': 'kumulos'});

// Inspect result.responseCode and result.payload

And you're done! You can now make calls to Kumulos from your Flutter application. The payload object returned by KumulosBackendClient.call can be either an array of objects (in case of a select action) or a number in case of other actions.

Crash

Crash reporting allows you to track unhandled exceptions in your app, and optionally log any caught exceptions for further investigation. Crash reporting is not enabled by default.

For Flutter, the crash reporting feature includes both native code crash reporting, and Dart error reporting. Native code crash reporting would catch crashes of the Flutter host process, whilst Dart error reporting catches unhandled errors in your application source code.

To get started, follow the steps below.

First, enable native crash reporting in your kumulos.json:

{
    "apiKey": "YOUR_API_KEY",
    "secretKey": "YOUR_SECRET_KEY",
    "enableCrashReporting": true, // Enable native crash reporting
    "inAppConsentStrategy": "in-app-disabled",
    "enableDeferredDeepLinking": false
}

Next, to catch errors from your Dart application code, implement the following handlers in your lib/main.dart main() function:

void main() {
  // Ensure the Flutter widgets are bound to the engine
  WidgetsFlutterBinding.ensureInitialized();
  // Run the Dart application in a zone to catch runtime errors
  runZonedGuarded(() {
    // Handle Flutter framework errors
    FlutterError.onError = Kumulos.onFlutterError;

    runApp(MyApp());
  }, Kumulos.logUncaughtError); // Handle uncaught zone errors
}

That's it! Unhandled exceptions that lead to crashes will now be recorded automatically and shown in your App Delivery Console.

If you wish to record non-fatal errors from expected error states, you can use Kumulos.logError():

Kumulos.logError("We knew about this one", StackTrace.current);

Changelog

See the Flutter SDK Changelog on GitHub.