Singular SDK Integration for Flutter

The Singular SDK is available as a plug-in for Flutter. The instructions below show you how to integrate Singular into your Flutter app.

Guide for Engineering Teams
Prerequisites
  • This article assumes you have a functional Flutter app.
  • To integrate the Singular SDK, you need to acquire your SDK Key and Secret. You can find them by logging into your Singular account and going to Settings > SDK Keys.

Integrating the Singular Plugin

To add the Singular plugin to your Flutter app, add the following lines to your pubspec.yaml file:

dependencies:
singular_flutter_sdk: ^0.0.3

Then navigate to your project in the terminal and run the following:

flutter packages get

Additional Steps for Android

For Android apps, you need to add the Singular library to the dependencies list in app/build.gradle, as follows:

dependencies {
      implementation 'com.google.android.gms:play-services:6.5.87'
      implementation fileTree(dir: 'libs', include: ['*.jar'])
      implementation 'com.android.support:appcompat-v7:21.0.3'
      ...
 }

If you have disabled transitive dependencies for the Singular SDK, add the following to your app's build.gradle:

com.android.installreferrer:installreferrer:2.1

If your app doesn't implement Google Play Services API 11.6.0 or higher, add the following dependency to your app's build.gradle:

implementation 'com.google.android.gms:play-services-ads:11.6.0'

Additional Steps for iOS

To use the Singular plugin, you have to add the AdServices framework.

Initializing the Singular SDK

The Singular SDK initialization code should be called every time your app is opened. It is a prerequisite to all Singular attribution functionality, and it also sends a new user session to Singular (sessions are used to calculate user retention).

The initialization code goes in your main app widget - the first one that loads when the app is opened. This widget has to be stateful, and the code has to be added in the widget's initState() method.

First, you have to create a SingularConfig object. The object contains your Singular SDK Key and Secret (which you acquired from the Singular web app - see the Prerequisites above).

Optionally, you can add settings to enable various SDK features. See the full list of options.

Example:

import 'package:singular_flutter_sdk/singular.dart';
import 'package:singular_flutter_sdk/singular_config.dart';

...

class MyHomePage extends StatefulWidget { 
    ...
}

class _MyHomePageState extends State<MyHomePage> {
    ...
    @ovveride 
          
    initState() {
            ...
            SingularConfig config = new SingularConfig('API_KEY', 'API_SECRET');
            config.customUserId = "test@test.com";
            Singular.start(config);
        }

Tracking Events

In addition to sending user sessions to Singular (through initializing the SDK), you can also send user events. Data about in-app events helps Singular analyze the performance of your user acquisition campaigns and measure KPIs. For example, your organization may want to collect data about user logins, registrations, tutorial completions, or leveling up in a gaming app.

To send events to Singular, use the event or eventWithArgs methods.

Example:

Singular.event(eventName);
Singular.eventWithArgs(eventName, {"level-up":"5"});

Tracking Revenue

Sending IAP Events

To let Singular track how much revenue your app is making, send IAP events to Singular. By sending the IAP event you also allow Singular to check the event verification data and make sure it's not fraudulent.

For example:

import 'package:singular_flutter_sdk/singular_iap.dart';
            import 'dart:io' show Platform;
          
            if (Platform.isIOS) {
             singularPurchase = new SingularIOSIAP(
               product.price,
               product.currencyCode,
               purchase.productId,
               purchase.purchaseId,
               purchase.verificationData.serverVerificationData
             );
            }
          
            else if (Platform.isAndroid) {
             singularPurchase = new SingularAndroidIAP(
               product.price,
               product.currencyCode,
               purchase.singature,
               purchase.verificationData.serverVerificationData
             );
            }
          
            Singular.inAppPurchase(eventName, singularPurchase);

Sending Custom Revenue Events (Not Recommended)

Singular also offers the option of reporting revenue by just sending a custom revenue event with a name and a revenue amount. This is less recommended because it gives Singular much less information and does not allow Singular to verify that it's a legitimate event.

For example:

 Singular.customRevenue("MyCustomRevenue", "USD", 5.50);

Implementing Deep Links

Deep links are links that open the app on the user's phone and send the user directly to a specific page or user experience, instead of just the app's main widget. Deep links are usually used in retargeting campaigns, aimed at users who already have the app on their phone but may not have engaged with it for a while. Singular supports deep linking through Singular Links.

Enabling Singular Links

To enable Singular Links in iOS and in Android, see Singular Links Prerequisites.

For Android support add the following code in the project's MainActivity.java file: 

import com.singular.flutter_sdk.SingularBridge;

            @Override
            protected void onNewIntent(@NonNull Intent intent) {
              super.onNewIntent(intent);
              SingularBridge.onNewIntent(intent);
            }

For iOS Support, in the project’s AppDelegate.m, add the following:

// Top of AppDelegate.m
          
#import "SingularAppDelegate.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];
  [SingularAppDelegate shared].launchOptions = launchOptions;
  return [super application:application didFinishLaunchingWithOptions:launchOptions];
  }
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> *restorableObjects))restorationHandler {
  [[SingularAppDelegate shared] continueUserActivity:userActivity restorationHandler:restorationHandler];
  return YES;
  }
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    [[SingularAppDelegate shared] handleOpenUrl:url options:options];
    return YES;
  }

Handling Singular Links

Use Singular's handler mechanism to read the details of the tracking link that led to the app being opened.

For example:

SingularConfig config = new SingularConfig('API_KEY', 'API_SECRET');
                config.singularLinksHandler = (SingularLinkParams params) {
                String deeplink = params.deeplink;
                String passthrough = params.passthrough;
                bool isDeferred = params.isDeferred;
                // Add your code here to handle the deep link
            });
        
            Singular.init(config);

Adding SKAdNetwork Support

To enable SKAdNetwork tracking for your app, enable the skAdNetworkEnabled configuration option before initializing Singular.

Managed Mode (Recommended)

In managed mode, Singular manages the SKAdNetwork conversion value for you automatically, based on a conversion model of your choice that you can set up in the Singular web app. 

To learn more, see Understanding Singular's Conversion Value Management and the SKAdNetwork Model Configuration FAQ. For a step-by-step guide t using SKAdNetwork with Singular, see How to Get Started with SKAdNetwork.

To enable SKAdNetwork in managed mode, use the following code:

SingularConfig config = new SingularConfig('API_KEY', 'API_SECRET');
config.skAdNetworkEnabled = true;
config.manualSkanConversionManagement = false;
Singular.init(config);

Manual Mode

If you already have your own strategy and tools for managing the SKAdNetwork conversion value, you can enable SKAdNetwork in manual mode.

SingularConfig config = new SingularConfig('API_KEY', 'API_SECRET');
config.skAdNetworkEnabled = true;
config.manualSkanConversionManagement = true;
Singular.init(config);

Then, to update the conversion value, use the following code:

ingular.skanUpdateConversionValue(conversionValue)

To track when the conversion value changes, use the following callback function:

config.conversionValueUpdatedCallback = (int conversionValue) {
     print('Received conversionValueUpdatedCallback: ' + conversionValue.toString());
};

To retrieve the current conversion value, use the following code:

Singular.skanGetConversionValue().then((conversionValue) {
     print('conversion value: ' + conversionValue.toString());
});

Tracking Uninstalls

To let Singular track app uninstalls, give Singular the APNS/FCM token, as in the following example:

// iOS
  Singular.registerDeviceTokenForUninstall(apnsToken);
          
// Android
  Singular.registerDeviceTokenForUninstall(fcmToken);
Was this article helpful?