Flutter SDK Installation and Setup

Install and set up the Flutter SDK.

This guide walks you through the SDK installation and initialization steps in detail.

Prerequisites

Flutter source write key

Installing the SDK

info
Starting from v1.0.2, the RudderStack Flutter SDK is migrated to Null Safety.

Follow these steps to add the Flutter SDK through pub:

  1. Open pubspec.yaml and add rudder_sdk_flutter under dependencies section:
dependencies:
  rudder_sdk_flutter: ^2.0.1
  1. Navigate to your application’s root folder and install all the required dependencies with the following command:
flutter pub get
info
If you are using Proguard full mode to optimize your app, add the lines specified in the FAQ to your Android ProGuard rules.

Installing the SDK for the web

To install and use the Flutter SDK in your web app, follow the above steps to add the Flutter SDK. Additionally, copy the following snippet in the <head> section of your web page:

<script>
rudderanalytics = window.rudderanalytics = [];
for (var methods = ["load", "page", "track", "identify", "alias", "group", "ready", "reset", "getAnonymousId", "setAnonymousId"], i = 0; i < methods.length; i++) {
  var method = methods[i];
  rudderanalytics[method] = function(a) {
    return function() {
      rudderanalytics.push([a].concat(Array.prototype.slice.call(arguments)))
    }
  }(method)
}
</script>

<script src="https://cdn.rudderlabs.com/v1/rudder-analytics.min.js"></script>
danger

Not all Flutter SDK APIs are applicable for the web. The following APIs will have no effect on your web app:

Initializing the SDK

  1. Import the SDK using the following snippet:
import 'package:rudder_sdk_flutter_platform_interface/platform.dart';
import 'package:rudder_sdk_flutter/RudderController.dart';
  1. Add the following code in your application:
final RudderController rudderClient = RudderController.instance;
RudderLogger.init(RudderLogger.VERBOSE);
RudderConfigBuilder builder = RudderConfigBuilder();
builder.withDataPlaneUrl(<DATA_PLANE_URL>);
builder.withTrackLifecycleEvents(true);
rudderClient.initialize(<WRITE_KEY>,config: builder.build());

The initialize method has the following signature:

NameTypeDescription
writeKey
Required
StringFlutter source’s write key.
configRudderConfigRudderStack client configuration.

SDK initialization options

You can configure the SDK behavior using the RudderConfig object passed to the rudderClient.initialize() call during initialization.

You can create the object of RudderConfig class by either:

  • Directly calling its constructor using the parameters documented below, or
  • Using the RudderConfigBuilder class APIs as per your requirement
RudderConfig constructor parameterRudderConfigBuilder class APIType
Description
Default value
dataPlaneUrlwithDataPlaneUrl()StringThe data plane URL.https://hosted.rudderlabs.com
flushQueueSizewithFlushQueueSize()intNumber of events in a batch request to the server.30
isDebugwithDebug()boolWhen enabled, sets the log level as debug. For more information, refer to the Debugging section.false
logLevelwithLogLevel()intControls the logs you want to see from the Flutter SDK.RudderLogger.RudderLogLevel.NONE
mobileConfigwithMobileConfig()MobileConfigRefer to the mobileConfig parameters section below.-
webConfigwithWebConfig()WebConfigRefer to the webConfig parameters section below.-
controlPlaneUrlwithControlPlaneUrl()StringThis parameter should be changed only if you are self-hosting the control plane. Refer to the Self-hosted control plane section for more information. The SDK will add /sourceConfig along with this URL to fetch the configuration.https://api.rudderlabs.com

mobileConfig parameters

The mobileConfig object contains the mobile-specific configuration parameters for the Flutter SDK.

ParameterTypeDescriptionDefault value
dbCountThresholdintNumber of events to be saved in the SQLite database. Once this limit is reached, the older events are deleted from the database.10000
sleepTimeOutintMinimum waiting time to flush the events to the server.10 seconds
configRefreshIntervalintFetches the config from the dashboard after this specified time.2
trackLifecycleEventsboolDetermines if the SDK will capture application life cycle events automatically.true
autoCollectAdvertIdboolDetermines if the SDK will collect the advertisement ID.false
recordScreenViewsboolWhen enabled, the SDK automatically records the screens viewed by the user.false
dbEncryptionRudderDBEncryptionSpecify whether to encrypt/decrypt the database using the specified key. See Encrypting RudderStack databases for more information.-

webConfig parameters

The webConfig object contains the configuration parameters for using the SDK in the Flutter web applications.

ParameterTypeDescriptionDefault value
destSDKBaseURLStringThe SDK loads the integration from this path.
useBeaconboolIf enabled, the SDK sends the event payloads via the navigator.sendBeacon() utilityFalse
secureCookieboolIf enabled, the SDK sends the cookie to the storage backend via HTTPS.False
loadIntegrationboolIf disabled, the destination SDKs are not fetched by the SDK.True
cookieConsentManagersObjectRefer to the cookieConsentManager section for more information.-
beaconFlushQueueIntervalintThe SDK flushes the queue after this time interval (in milliseconds).600000
maxBeaconItemsintThe SDK flushes the queue when this number of events is reached.10
maxItemsintMaximum number of events kept in the storage.100
maxAttemptsintMaximum number of attempts the SDK makes to send the event to the destination.10
backoffFactorintRefers to the exponential base.2
minRetryDelayintThe minimum delay expected before the SDK retries sending an event (in ms)1000
maxRetryDelayintThe upper limit on the maximum delay for retrying an event (in ms)360000
info
You can also enable or disable events for specific destinations while initializing the SDK.

Self-hosted control plane

If you are self-hosting RudderStack and using the Control plane lite utility to host your own control plane, then follow the steps in this section and specify the controlPlaneUrl parameter in your RudderConfigBuilder that points to the hosted configuration file.

danger
You should not pass the controlPlaneUrl parameter during SDK initialization if you are using RudderStack Cloud. This parameter is supported only if you are using the open source Control plane lite utility to set up your own control plane.

FAQ

Do I need to add anything to my Android ProGuard rules?

If you are using Proguard full mode to optimize your app, add the following lines to your Android ProGuard rules:

// Reporter Module
-keep class com.rudderstack.android.ruddermetricsreporterandroid.models.LabelEntity { *; }
-keep class com.rudderstack.android.ruddermetricsreporterandroid.models.MetricEntity { *; }
-keep class com.rudderstack.android.ruddermetricsreporterandroid.models.ErrorEntity { *; }

// Required for the usage off TypeToken class in Utils.converToMap, Utils.convertToList
-keep class com.google.gson.reflect.TypeToken { *; }
-keep class * extends com.google.gson.reflect.TypeToken

// Required for the serialization of SourceConfig once it is downloaded.
-keep class com.google.gson.internal.LinkedTreeMap { *; }
-keep class * implements java.io.Serializable { *; }
-keep class com.rudderstack.rudderjsonadapter.RudderTypeAdapter { *; }
-keep class * extends com.rudderstack.rudderjsonadapter.RudderTypeAdapter

// Required to ensure the DefaultPersistenceProviderFactory is not removed by Proguard 
// and works as expected even when the customer is not using encryption feature.
-dontwarn net.sqlcipher.Cursor
-dontwarn net.sqlcipher.database.SQLiteDatabase$CursorFactory
-dontwarn net.sqlcipher.database.SQLiteDatabase
-dontwarn net.sqlcipher.database.SQLiteOpenHelper
-keep class com.rudderstack.android.sdk.core.persistence.DefaultPersistenceProviderFactory { *; }

// Required for the usage of annotations across reporter and web modules
-dontwarn com.fasterxml.jackson.annotation.JsonIgnore
-dontwarn com.squareup.moshi.Json
-dontwarn com.fasterxml.jackson.annotation.JsonProperty

// Required for Device Mode Transformations
-keep class com.rudderstack.android.sdk.core.TransformationResponse { *; }
-keep class com.rudderstack.android.sdk.core.TransformationResponseDeserializer { *; }


Questions? Contact us by email or on Slack