# Flutter SDK v1

The **RudderStack Flutter SDK** lets you track event data from your Flutter applications and send it to your specified destinations via RudderStack.

Refer to the [Flutter SDK GitHub Repository](https://github.com/rudderlabs/rudder-sdk-flutter) to get a more hands-on understanding of the SDK and the related codebase.

{{< version-badge label="pub" prefix="v" fallback="1.2.0" href="https://pub.dev/packages/rudder_sdk_flutter/versions/1.2.0" >}}

{{< warning >}}
It is strongly recommended to update your Flutter SDK to the latest version to get all the features, including **web support**. Refer to the [SDK documentation]({{< ref "sources/event-streams/sdks/rudderstack-flutter-sdk/" >}}) for more information.
{{< /warning >}}

## SDK setup requirements

To set up the RudderStack Flutter SDK, you need the following prerequisites:

- Sign up for [RudderStack](https://app.rudderstack.com).
- [Set up a Flutter source]({{< ref "dashboard-guides/sources/_index.md#adding-a-source" >}}) in the dashboard. Note the {{< glossary_tooltip "write-key" >}} for this source.
- You will also need the [data plane URL]({{< ref "dashboard-guides/_index.md#connections" >}}) associated with your RudderStack workspace.
- It is also recommended to set up the [Flutter development environment](https://flutter.dev/docs/get-started/install) in your system.

{{< success >}}
Starting from v1.0.2, the RudderStack Flutter SDK is migrated to Null Safety.
{{< /success >}}

## Installing the RudderStack Flutter SDK

The recommended way to install the Flutter SDK is through [`pub`](https://pub.dev/packages/rudder_sdk_flutter).

Follow the steps below to add the SDK as a dependency:

1. Open `pubspec.yaml` and add `rudder_sdk_flutter` under `dependencies` section:

```yaml
dependencies:
  rudder_sdk_flutter: ^1.2.0
```

2. Navigate to your application's root folder and install all required dependencies with the following command:

```bash
flutter pub get
```

## Initializing the RudderStack client

After adding the SDK as a dependency, you need to set up the SDK.

1. To import the SDK, use the following snippet:

```dart
import 'package:rudder_sdk_flutter/RudderClient.dart';
import 'package:rudder_sdk_flutter/RudderConfig.dart';
import 'package:rudder_sdk_flutter/RudderLogger.dart';
```

2. Then, add the following code snippet in your application:

```dart
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:

| Name       | Type      | Presence | Description                                   |
| :--------- | :------------- | :------- | :-------------------------------------------- |
| `writeKey` | String       | Required      | Your Flutter source write key.                       |
| `config`   | `RudderConfig` | Optional       | Contains the RudderStack client configuration |

{{< info >}}
Check the [Configuring your RudderStack client](#configuring-your-rudderstack-client) section below for a complete list of the configurable parameters.
{{< /info >}}

## Configuring your RudderStack Client

You can configure your client based on the following parameters by passing them in the `RudderConfigBuilder` object of your `rudderClient.initialize()` call.

| Parameter  | Type      | Description      | Default value   |
| :---------- | :-------- | :--------- | :----------------- |
| `logLevel`              | Integer     | Controls how much of the log you want to see from the Flutter SDK. | `RudderLogger.RudderLogLevel.NONE`                       |
| `dataPlaneUrl`           | String  | Your {{< glossary_tooltip "data-plane-url" >}} | - |
| `flushQueueSize`        | Integer     | Number of events in a batch request to the server. | `30`                                                     |
| `dbThresholdCount`      | Integer     | Number of events to be saved in the SQLite database. Once this limit is reached, the older events are deleted from the database.        | `10000` |
| `sleepTimeout`          | Integer     | Minimum waiting time to flush the events to the server.                                                                                                                                                                                           | `10 seconds`                                             |
| `configRefreshInterval` | Integer     | Fetches the config from the dashboard after this specified time.                                                      | `2`                                                      |
| `trackLifecycleEvents`  | Boolean | Determines if the SDK will capture application life cycle events automatically.                                     | `true`                                                   |
| `autoCollectAdvertId` | Boolean | Determines if the SDK will collect the advertisement ID. | `false` |
| `controlPlaneUrl`       | String  | This parameter should be changed **only if** you are self-hosting the control plane. Check the section [Self-hosted control plane](#self-hosted-control-plane) section below for more information. The SDK will add `/sourceConfig` along with this URL to fetch the configuration. | `https://api.rudderlabs.com` |

## Identify

RudderStack captures `deviceId` and uses that as the `anonymousId` for identifying the user. This helps to track the users across the application installation. To attach more information to the user, you can use the `identify` method.

For a detailed explanation of the `identify` call, refer to the [RudderStack API Specification]({{< ref "event-spec/standard-events/identify.md" >}}).

Once a user is identified, the SDK persists all user information and passes it to the successive  `track` or `screen` calls. To reset the user identification, you can use the `reset` method.

{{< info >}}
On the Android devices, the `deviceId` is assigned during the first boot. It remains consistent across the applications and installs. This can be changed only after a factory reset of the device.
{{< /info >}}

{{< info >}}
According to the [Apple documentation](https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor), if the iOS device has multiple apps from the same vendor, all apps will be assigned the same `deviceId`. If all applications from a vendor are uninstalled and then reinstalled, then they will be assigned a new `deviceId`.
{{< /info >}}

A sample `identify` event is as shown:

```dart
RudderTraits traits = RudderTraits();
traits.putBirthdayDate(new DateTime.now());
traits.putEmail("abc@123.com");
traits.putFirstName("Alex");
traits.putLastName("Keener");
traits.putGender("M");
traits.putPhone("1234567890");

Address address = Address();
address.putCity("New Orleans");
address.putCountry("USA");
traits.putAddress(address);

traits.put("boolean", true);
traits.put("integer", 50);
traits.put("float", 120.4);
traits.put("long", 1234);
traits.put("string", "hello");
traits.put("date", new DateTime.now().millisecondsSinceEpoch);

rudderClient.identify("test_user_id", traits: traits, options: null);
```

The `identify` method has the following signature:

| Name      | Data Type      | Presence | Description                                     |
| :-------- | :------------- | :------- | :---------------------------------------------- |
| `userId`  | String      | Required      | Includes the developer identity for the user.    |
| `traits`  | `RudderTraits` | Optional       | Contains information related to the user traits. |
| `options` | `RudderOption` | Optional       | Extra options for the `identify` event.         |

### Obtaining user traits after making an `identify` call

You can obtain the user traits after making an `identify` call as shown:

```dart
Map context = await rudderClient.getRudderContext();
print(context["traits"]);
```

## Track

You can record the users' activity through the `track` method. Each user action is called an event.

For a detailed explanation of the `track` call, refer to the [RudderStack API Specification]({{< ref "event-spec/standard-events/track.md" >}}).

A sample `track` event is shown below:

```dart
RudderProperty property = RudderProperty();
property.put("test_key_1", "test_key_1");
RudderProperty childProperty = RudderProperty();
childProperty.put("test_child_key_1", "test_child_value_1");
property.put("test_key_2",childProperty);
rudderClient.track("test_track_event", properties: property);
```

The `track` method has the following signature:

| Name         | Type        | Presence  | Description   |
| :----------- | :--------------- | :------- | :----------------------------------------------------------------------- |
| `name`       | String         | Required      | Contains the name of the event you want to track.                         |
| `properties` | `RudderProperty` | Optional       | Contains the extra properties you want to send along with the event. |
| `options`    | `RudderOption`   | Optional       | Contains the extra event options.                                        |

{{< info >}}
RudderStack automatically tracks the following **optional** [application lifecycle events]({{< ref "event-spec/standard-events/application-lifecycle-events-spec.md" >}}):

- [`Application Installed`]({{< ref "event-spec/standard-events/application-lifecycle-events-spec.md#application-installed" >}})
- [`Application Updated`]({{< ref "event-spec/standard-events/application-lifecycle-events-spec.md#application-updated" >}})
- [`Application Opened`]({{< ref "event-spec/standard-events/application-lifecycle-events-spec.md#application-opened" >}})
- [`Application Backgrounded`]({{< ref "event-spec/standard-events/application-lifecycle-events-spec.md#application-backgrounded" >}})

You can disable these events by calling `withTrackLifeCycleEvents(false)` in the `RudderConfigBuilder` object while initializing the RudderStack client. However, it is highly recommended to keep them enabled.
{{< /info >}}

## Screen

You can use the `screen` call to record whenever the user views a screen on their mobile device along with the properties associated with that event.

For a detailed explanation of the `screen` call, refer to the [RudderStack API Specification]({{< ref "event-spec/standard-events/screen.md" >}}) guide.

A sample `screen` event is as shown:

```dart
RudderProperty screenProperty = new RudderProperty();
screenProperty.put("foo", "bar");
rudderClient.screen("Main Activity",
    properties: screenProperty, options: null);
```

The `screen` method has the following signature:

| Name         | Type        | Presence | Description  |
| :----------- | :--------------- | :------- | :------------------------------------------------------------------------ |
| `screenName` | String        | Required      | Name of the screen viewed by the user.                                                |
| `properties` | `RudderProperty` | Optional       | Extra property object that you want to pass along with the `screen` call. |
| `options`    | `RudderOption`   | Optional       | Extra options to be passed along with `screen` event.                     |

## Group

The `group` call associates a user to a specific organization.

For a detailed explanation of the `group` call, refer to the [RudderStack Event Specification]({{< ref "event-spec/standard-events/group.md" >}}) guide.

A sample `group` event is shown below:

```dart
RudderTraits groupTraits = RudderTraits();
groupTraits.put("foo", "bar");
groupTraits.put("foo1", "bar1");
rudderClient.group("sample_group_id",
    groupTraits: groupTraits, options: null);
```

The `group` method has the following signature:

| Name          | Type      | Presence | Description         |
| :------------ | :------------- | :------- | :------------------------- |
| `groupId`     | `String`       | Required      | The ID of the organization with which you want to associate your user.               |
| `groupTraits` | `RudderTraits` | Optional       | Any other organization traits you want to pass along with the `group` call. |
| `options`     | `RudderOption` | Optional       | Extra options to be passed along with `group` event.                               |

{{< info >}}
RudderStack doesn't persist the group traits across the sessions.
{{< /info >}}

## Alias

The `alias` call lets you merge different identities of a known user.

{{< info >}}
`alias` is an advanced method that lets you change the tracked user's ID explicitly. This method is useful when managing identities for some of the downstream destinations.
{{< /info >}}

For a detailed explanation of the `alias` call, refer to the [RudderStack Event Specification]({{< ref "event-spec/standard-events/alias.md" >}}) guide.

A sample `alias` call is as shown:

```dart
rudderClient.alias("new_user_id", options: null);
```

The `alias` method has the following signature:

| Name      | Data Type      | Presence | Description                                          |
| :-------- | :------------- | :------- | :--------------------------------------------------- |
| `newId`   | String       | Required      | The new `userId` you want to assign to the user.      |
| `options` | `RudderOption` | Optional       | Extra options to be passed along with `alias` event. |

{{< info >}}
RudderStack replaces the old `userId` with the `newUserId` and persists this identification across the sessions.
{{< /info >}}

## Reset

You can use the `reset` method to clear the persisted `traits` for the `identify` call. This is required for scenarios where the user logs out of a session.

```dart
rudderClient.reset();
```

## Enabling/disabling user tracking via the `optOut` API(GDPR support)

RudderStack gives the users \(for example, an EU user\) the ability to opt out of tracking any user activity until the user gives their consent. You can do this by leveraging RudderStack's `optOut` API.

The `optOut` API takes `true` or `false` as a Boolean value to enable or disable tracking user activities. This flag persists across device reboots.

The following snippet highlights the use of the `optOut` API to disable user tracking:

```dart
rudderClient.optOut(true);
```

Once the user grants their consent, you can enable user tracking once again by using the `optOut` API with `false` as a parameter sent to it:

```dart
rudderClient.optOut(false);
```

{{< info >}}
The `optOut` API is available in the Flutter SDK starting from version `1.0.6`.
{{< /info >}}

## Filtering events

When sending events to a destination via [device mode]({{< ref "destinations/rudderstack-connection-modes.md#device-mode" >}}), you can explicitly specify the events to be discarded or allowed to flow through by allowlisting or denylisting them.

Refer to the [Client-side Event Filtering]({{< ref "sources/event-streams/sdks/event-filtering.md" >}}) guide for more information on this feature.

## Enabling/disabling events for specific destinations

The Flutter SDK lets you enable or disable sending events to a specific destination or all destinations connected to a source. You can specify these destinations by creating an object as shown in the following snippet:

```dart
RudderOption options = new RudderOption();
// default value for `All` is true
options.putIntegration("All", false);
// specifying destination by its display name
options.putIntegration("Mixpanel", false);
// specifying destination by its Factory object
options.putIntegrationWithFactory(Appcenter(), true);
```

{{< info >}}
The keyword `All` in the above snippet represents all destinations connected to a source. Its value is set to `true` by default.
{{< /info >}}

{{< info >}}
Make sure the destination names that you pass while specifying the destinations exactly match the names as listed in the [RudderStack dashboard](https://app.rudderstack.com/directory).
{{< /info >}}

You can pass the destinations to the SDK in the following two ways:

### Method 1. Passing destinations while initializing the SDK

This is helpful when you want to enable/disable sending the events across all event calls made using the SDK to the specified destination\(s\).

```dart
rudderClient.initialize(<WRITE_KEY>,
                    config: builder.build(),options: options);
```

### Method 2. Passing destinations while making event calls

This approach is helpful when you want to enable/disable sending only a particular event to the specified destination\(s\) or if you want to override the specified destinations passed with the SDK initialization for a particular event.

```dart
RudderProperty property = RudderProperty();
property.put("test_key_1", "test_key_1");
rudderClient.track("test_track_event", properties: property, options: options);
```

{{< warning >}}
If you specify the destinations both while initializing the SDK as well as while making an event call, then the destinations specified at the event level only will be considered.
{{< /warning >}}

## Setting a custom ID

You can pass a custom ID along with the standard `userId` in your `identify` calls. RudderStack adds this value under `context.externalId`.

{{< warning >}}
RudderStack supports passing `externalId` only in the `identify` events. You must not pass this ID in other API calls like `track`, `page`, etc.
{{< /warning >}}

The following snippet shows how to add `externalId` to your `identify` event:

```dart
RudderOption option = RudderOption();
option.putExternalId("externalId", "some_external_id_1");
rudderClient.identify("1hKOmRA4GRlm", options: option);
```

## Setting your own `anonymousId` using `putAnonymousId`

By default, RudderStack uses `deviceId` as `anonymousId`. You can use the following method to override and set your own `anonymousId` with the SDK:

```dart
rudderClient.putAnonymousId(<ANONYMOUS_ID>);
```

## Setting the advertisement ID

RudderStack collects the advertisement ID **only** if `autoCollectAdvertId` is set to `true` during the [SDK initialization](#initializing-the-rudderstack-client):

```dart
final RudderController rudderClient = RudderController.instance;
MobileConfig mobileConfig = MobileConfig(autoCollectAdvertId: true);
RudderLogger.init(RudderLogger.VERBOSE);
RudderConfigBuilder builder = RudderConfigBuilder();
builder.withDataPlaneUrl(<DATA_PLANE_URL>);
builder.withTrackLifecycleEvents(true);
rudderClient.initialize(<WRITE_KEY>,config: builder.build());
```

You can use the `putAdvertisingId` method to pass your Android and iOS AAID and IDFA respectively. 

The `putAdvertisingId` method accepts a string argument as listed below:

- `id` : Your Android advertisement ID (AAID) or your iOS advertisement ID (IDFA).

The following snippet highlights the use of `putAdvertisingId()`:

```dart
rudderClient.putAdvertisingId(<ADVERTISING_ID>);
```

{{< info >}}
The `id` parameter that you pass in the `putAdvertisingId` method is assigned as the AAID (for Android) or as the IDFA (for iOS).
{{< /info >}}

## Setting the device token

You can pass your device token for push notifications to be passed to the destinations which support the Push Notification feature. RudderStack sets the token under `context.device.token`.

An example of setting the device token is as shown below:

```dart
rudderClient.putDeviceToken(<DEVICE_TOKEN>);
```

### Self-hosted control plane

In case you are using a device mode destination like Adjust, Firebase, etc., the Flutter SDK needs to fetch the required configuration from the control plane. If you are using the [Control plane lite](https://github.com/rudderlabs/config-generator#rudderstack-control-plane-lite) utility to host your own control plane, then follow the steps in [this section]({{< ref "/get-started/rudderstack-open-source/control-plane-lite.md#using-sdk-sources-set-up-in-self-hosted-control-plane" >}}) and specify `controlPlaneUrl` in your [`RudderConfig.Builder`](#configuring-your-rudderstack-client) that points to your hosted source configuration file.

{{< danger >}}
Do not pass the `controlPlaneUrl` parameter during SDK initialization if you are using the [RudderStack dashboard](https://app.rudderstack.com). This parameter is supported only if you are using the open source [Control plane lite](https://github.com/rudderlabs/config-generator#rudderstack-control-plane-lite) utility to set up your own control plane.
{{< /danger >}}

## Debugging

If you run into any issues when using the Flutter SDK, you can turn on the `VERBOSE` or `DEBUG` logging to determine the issue. To do so, follow these steps:

1. First, make sure you import `RudderLogger` by running the following command:

```dart
import 'package:rudder_sdk_flutter/RudderLogger.dart';
```

2. Then, turn on the logging by changing your `rudderClient` initialization as shown:

```dart
RudderConfigBuilder builder = RudderConfigBuilder();
builder.withDataPlaneUrl(DATA_PLANE_URL);
builder.withLogLevel(RudderLogger.VERBOSE);
rudderClient.initialize(WRITE_KEY,config: builder.build());
```

You can set the log level to one of the following values:

- `NONE`
- `ERROR`
- `WARN`
- `INFO`
- `DEBUG`
- `VERBOSE`

## FAQ

#### How do I get the user `traits` after making an `identify` call?

You can get the user traits after making an `identify` call in the following way:

```dart
Map context = await rudderClient.getRudderContext();
print(context["traits"]);
```

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

If you are facing any event delivery issues in your production environment, verify if you have added the following line in your ProGuard rules:

```java
// 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 { *; }
```

