> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sprig.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Flutter Plugin

# Getting Started

### Overview

The Sprig Flutter plugin, when installed in app, allows you to track your customer’s in-product behavior and display Sprig studies when they perform certain actions.

### Requirements

* Join your teammates on [Sprig](https://app.sprig.com) (check with your Sprig admin whether team discovery is on, or simply have a team member invite you via your email address). This will give you access to your team’s environment IDs, as well as the [interactive Installation Guide](https://app.sprig.com/integrations/installation/react-native-module).
* Ensure you have access to your Flutter codebase, and can deploy to a development and/or production environment
* Please check the platform-specific requirements:
  * [iOS](/docs/Installation/introduction-mobile/ios-sdk-installation#requirements): iOS 15 or above; Xcode 16
  * [Android](/docs/Installation/introduction-mobile/android-sdk-installation/index#requirements): Android 5.1(22): Android Studio 2024.2.2

# Setup

### Obtain an Environment ID

Sprig provides two environments, Development and Production, each with its own corresponding ENVIRONMENT\_ID (which can be found in [any of the installation methods](https://app.sprig.com/integrations/installation)).

The Development environment is recommended for initially setting up and verifying your installation. Then, you can use the Production environment to deploy studies to real users.

### Add a reference to flutter-sprig

The Sprig Flutter plugin ([flutter-sprig](https://github.com/UserLeap/flutter-sprig/)) is hosted in a [github repository](https://github.com/UserLeap/flutter-sprig/) where it can be easily referenced from within your Flutter application.

In your **pubspec.yaml** file, add a reference to Sprig in your dependancies. The entry should look like this when you are done:

```yaml theme={null}
dependencies:  
  flutter:  
    sdk: flutter

  sprig_flutter_plugin:
		git:
      url: https://github.com/UserLeap/flutter-sprig
```

One that is in place, in a CLI that has a path to the Flutter SDK, run at the root of the plugin example project:

```bash theme={null}
flutter pub get
```

When installing for iOS, you need to do `pod install`. And if you are updating, it's best to remove the `Podfile.lock` and run `pod repo update` first. So from your app top-level directory, run the following commands:

```bash theme={null}
cd example
cd ios
rm Podfile.lock
pod repo update
pod install
```

### Full main.dart example

Following is a full example of a main.dart file that includes initializing the plugin, checking the version and calling trackAndPresent with an event code to display a survey.

```cplusplus Dart theme={null}
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:sprig_flutter_plugin/sprig_flutter_plugin.dart';
import 'package:sprig_flutter_plugin/sprig_types.dart';

void main() {
  runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _sdkVersion = "";
  final _sprigFlutterPlugin = SprigFlutterPlugin();
  
  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  Future<void> initPlatformState() async {
    String sdkVersion = "";
    try {
      _sprigFlutterPlugin.configure(environment: "<YOUR_ENVIRONMENT_ID>", configuration: null);
      sdkVersion = await _sprigFlutterPlugin.sdkVersion() ?? "";
      _sprigFlutterPlugin.registerEventListener(SprigLifecycleEvent.sdkReady, (Map<Object?, Object?> eventData) async {
        print("SDK is ready");
      });
    } on PlatformException catch (e) {
      print('PlatformException: ${e.message}');
    }

    if (!mounted) return;
    setState(() {
      _sdkVersion = sdkVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('A Flutter App'),
        ),
        body: Container(
          margin: const EdgeInsets.only(left: 16.0),
            child: ListView(
            padding: const EdgeInsets.all(8),
            children: <Widget>[
              Text('Sprig SDK version: $_sdkVersion'),

              // Spacer
              SizedBox(height: 20),

              // Button to present a survey by supplied ID
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () {
                    _sprigFlutterPlugin.trackAndPresent(eventName:  "<YOUR_SURVEY_EVENT>");
                  },
                  child: Text("Call trackAndPresent"),
                ),
              ),
            ],
            ),
        )
      ),
    );
  }
}
```

Be sure to swap in the correct environment ID for YOUR\_ENVIRONMENT\_ID. Note that `configure()` will only accept 1 environment ID, and calling it multiple times with different IDs will have no effect.

# Additional Functionality

<Note>
  Note that the remaining examples use **\_sprigFlutterPlugin** when calling the plugin, assuming you have set **\_sprigFlutterPlugin** to **SprigFlutterPlugin()** as in the above code.
</Note>

<br />

## Identify Users

Identifying users ensures that a user’s actions are all associated with the same profile so they can be targeted.

Properly identifying users helps ensure:

* Your users have a consistent experience across platforms, and do not see the same study multiple times
* You can accurately target the right users
* You are billed for the correct number of [Monthly Unique Users (MUUs)](/docs/account-and-settings/usage-muu/index)

### Set User ID

Sprig allows you to differentiate users by setting a unique USER\_ID.  You may want to ensure consistency between the User IDs sent to Sprig and the ones in your internal database, product analytics/CDP, or data warehouse. You can also use an [anonymizing function or hash](https://docs.google.com/document/d/1qMO3DaXklt9csAPfWNolBpPecAiQ55350ke2_nwFSAs/edit).

A good User ID is…

* Unique: Two users should not share the same User ID.
* Mappable: User IDs sent to Sprig should map back to your internal User IDs, either directly or anonymously.
* Static: Once assigned, a User ID should not change.

Users that do not have a User ID set are considered unauthenticated.

You can use `setUserIdentifier()` to identify a user with any string less than 256 characters. This function can be called multiple times safely, and stores the identifier via local storage. We recommend you set the User ID whenever the user logs in to your app, as well as after the installation snippet (if the user is already logged in).

```cplusplus Dart theme={null}
_sprigFlutterPlugin.setUserIdentifier(identifier: "<YOUR_USER_ID>");
```

### Logout

When a user logs out of your app, make sure to log out of Sprig. This will prevent new activity from being associated with an incorrect user. Note that if you call `logout()` on an unauthenticated user, Sprig will assign them a new profile and count this new user separately toward your MTU limit.

```cplusplus Dart theme={null}
_sprigFlutterPlugin.logout();
```

## Track Events

Sprig uses events to **trigger** (display) studies after the user performs a specific action. They can also be used as a **filter** to target users who have previously performed an action.

Once you’ve installed the Sprig SDK, the next step is to configure the tracking of events that you would like to use to trigger a study. For mobile SDKs, you must configure [Code](/docs/shared-study-foundations/events/code-events) events. (Sprig also offers [No-Code](/docs/shared-study-foundations/events/no-code-events) events, but these are only available on web platforms.)

To track a Code event, use:

```cplusplus Dart theme={null}
SizedBox(
        width: double.infinity,
        child: ElevatedButton(
          onPressed: () {
            _sprigFlutterPlugin.track(eventName: "<YOUR_SURVEY_EVENT>", onCompletion: (surveyState) {
                debugPrint("Track completed with survey state: $surveyState");
                if (surveyState == SprigSurveyState.ready) {
                  _sprigFlutterPlugin.present();
                }
              });
          },
          child: const Text('Track with callback and then present'),
        ),
  ),
```

After sending a new Code event to Sprig, you must [approve the new event request](/docs/shared-study-foundations/events/index#adding-events) on the [Events page](https://app.sprig.com/events) before it can be used to trigger or filter surveys.

These events will also be available as filters for your studies. For example, you may want to only display a study to users who have performed the "checkout" event at least 3 times.

## Track Attributes

Sprig allows you to track **attributes**, which can provide more context about the user to help you better understand their feedback. You can also use these attributes to [filter](/docs/shared-study-foundations/main-tasks/study-triggers-user-filters-and-groups-copy#survey-filter) your audience and target specific kinds of users. Some example attributes that can be tracked are:

* Plan type
* Super users / power users
* Company

A user’s attributes can be seen on their profile in the Users page, and are recorded and attached to any surveys response they submit. For more information, see [Attributes](/docs/shared-study-foundations/attributes).

To set user attributes, provide the SDK with a key-value pairs:

* `ATTRIBUTE_NAME` must be a string less than 256 characters, and cannot start with an `!` (these names are reserved for use by Sprig)
* `ATTRIBUTE_VALUE` must be a number, boolean, or string less than 256 characters

```cplusplus Dart theme={null}
_sprigFlutterPlugin.setVisitorAttribute(key: "<YOUR_ATTRIBUTE_KEY>", value: "<YOUR_ATTRIBUTE_VALUE>");

// if attributes no longer apply to the user,
// you can delete multiple at a time
_sprigFlutterPlugin.removeVisitorAttributes(attributes:["<YOUR_ATTRIBUTE_KEY1>", "<YOUR_ATTRIBUTE_KEY2>"]);
```

### Set Email Address

Setting the user’s email address is **optional**. Setting emails is not required for web or mobile studies, but can be used to target users or create a Group of users based on their email. Check your organization's guidelines around personally-identifiable information before sending email addresses to Sprig.

```cplusplus Dart theme={null}
_sprigFlutterPlugin.setEmailAddress(emailAddress: <YOUR_VISITOR_EMAIL_ADDRESS>);
```

## Test & Deploy

To verify your SDK is configured properly, we recommend testing with your development `ENVIRONMENT_ID`.

1. Create a survey in your Sprig Development Environment
2. Choose an approved event as a trigger for your study
3. \[For testing purposes only] Allow users to retake the survey and set the recontact waiting period to 0 days

<img align="center" alt="Image 2354" title="Screenshot 2023-01-26 at 4.39.52 PM.png" src="https://mintcdn.com/sprig/_ephcOEAcdx-CRO7/images/2991e4b-Screenshot_2023-01-26_at_4.39.52_PM.png?fit=max&auto=format&n=_ephcOEAcdx-CRO7&q=85&s=38b137a8468dcbd7f739576c1358b0f0" width="2354" height="658" data-path="images/2991e4b-Screenshot_2023-01-26_at_4.39.52_PM.png" />

4. Track the approved event from your app and confirm that the survey appears

Congratulations! Your installation is complete and you can begin deploying.
