Segment plugin

Pub Version

Flutter plugin to support iOS, Android and Web sources at https://segment.com.

Usage

To use this plugin, add flutter_segment as a dependency in your pubspec.yaml file.

Supported methods

MethodAndroidiOSWeb
identifyXXX
trackXXX
screenXXX
groupXXX
aliasXXX
getAnonymousIdXXX
resetXXX
disableXX
enableXX
debugX*XX
setContextXX

* Debugging must be set as a configuration parameter in AndroidManifest.xml (see below). The official segment library does not offer the debug method for Android.

Example

import 'package:flutter/material.dart';
import 'package:flutter_segment/flutter_segment.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Segment.screen(
      screenName: 'Example Screen',
    );
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Segment example app'),
        ),
        body: Center(
          child: FlatButton(
            child: Text('TRACK ACTION WITH SEGMENT'),
            onPressed: () {
              Segment.track(
                eventName: 'ButtonClicked',
                properties: {
                  'foo': 'bar',
                  'number': 1337,
                  'clicked': true,
                },
              );
            },
          ),
        ),
      ),
      navigatorObservers: [
        SegmentObserver(),
      ],
    );
  }
}

Installation

Setup your Android, iOS and/or web sources as described at Segment.com and generate your write keys.

Set your Segment write key and change the automatic event tracking (only for Android and iOS) on if you wish the library to take care of it for you. Remember that the application lifecycle events won't have any special context set for you by the time it is initialized.

To enable branch.io integration you need to configure ENABLE_BRANCH_IO_INTEGRATION as mentioned in the next section.

Android

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.flutter_segment_example">
    <application>
        <activity>
            [...]
        </activity>
        <meta-data android:name="com.claimsforce.segment.WRITE_KEY" android:value="YOUR_WRITE_KEY_GOES_HERE" />
        <meta-data android:name="com.claimsforce.segment.TRACK_APPLICATION_LIFECYCLE_EVENTS" android:value="false" />
        <meta-data android:name="com.claimsforce.segment.ENABLE_BRANCH_IO_INTEGRATION" android:value="false" />
        <meta-data android:name="com.claimsforce.segment.DEBUG" android:value="false" />
    </application>
</manifest>

iOS

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	[...]
	<key>com.claimsforce.segment.WRITE_KEY</key>
	<string>YOUR_WRITE_KEY_GOES_HERE</string>
	<key>com.claimsforce.segment.TRACK_APPLICATION_LIFECYCLE_EVENTS</key>
	<false/>
	<key>com.claimsforce.segment.ENABLE_BRANCH_IO_INTEGRATION</key>
	<false/>
	[...]
</dict>
</plist>

Web

<!DOCTYPE html>
<html>
<head>
  [...]
</head>
<body>
<script>
  !function(){ ...;
    analytics.load("YOUR_WRITE_KEY_GOES_HERE");
    analytics.page();
  }}();
</script>
  <script src="main.dart.js" type="application/javascript"></script>
</body>
</html>

For more informations please check: https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/quickstart/

Sending device tokens strings for push notifications

Segment integrates with 3rd parties that allow sending push notifications. In order to do that you will need to provide it with the device token string - which can be obtained using one of the several Flutter libraries.

As soon as you obtain the device token string, you need to add it to Segment's context by calling setContext and then emit a tracking event named Application Opened or Application Installed. The tracking event is needed because it is the only moment when Segment propagates it to 3rd parties.

Both calls (setContext and track) can be done sequentially at startup time, given that the token exists. Nonetheless, if you don't want to delay the token propagation and don't mind having an extra Application Opened event in the middle of your app's events, it can be done right away when the token is acquired.

await Segment.setContext({
  'device': {
    'token': yourTokenString
  },
});

// the token is only propagated when one of two events are called:
// - Application Installed
// - Application Opened
await Segment.track(eventName: 'Application Opened');

A few important points:

  • The token is propagated as-is to Segment through the context field, without any manipulation or intermediate calls to Segment's libraries. Strucutred data - such as APNs - need to be properly converted to its string representation beforehand
  • On iOS, once the device.token is set, calling setContext({}) will not clean up its value. This occurs due to the existence of another method from segment's library that sets the device token for Apple Push Notification service (APNs )
  • setContext always overrides any previous values that were set in a previous call to setContext
  • setContext is not persisted after the application is closed

Setting integration options

If you intend to use any specific integrations with third parties, such as custom Session IDs for Amplitude, you'll need to set it using options for each call, or globally when the application was started.

Setting the options in every call

The methods below support options as parameters:

  • identify({@required userId, Map<String, dynamic> traits, Map<String, dynamic> options})
  • track({@required String eventName, Map<String, dynamic> properties, Map<String, dynamic> options})
  • screen({@required String screenName, Map<String, dynamic> properties, Map<String, dynamic> options})
  • group({@required String groupId, Map<String, dynamic> traits, Map<String, dynamic> options})
  • alias({@required String alias, Map<String, dynamic> options})

An example of a screen being tracked as part of a session, which will be communicated to Amplitude:

Segment.screen(
  screenName: screenName,
  properties: {},
  options: {
    'integrations': {
      'Amplitude': {'session_id': '1578083527'}
    }
  },
)

Setting the options globally

You can also set the default options to be used in every method call, if the call omits the options parameter. Just set SegmentDefaultOptions.instance.options. For example:

SegmentDefaultOptions.instance.options = {
  'integrations': {
    'Amplitude': {
      'session_id': '1578083527'
    }
  }
}

Issues

Please file any issues, bugs, or feature requests in the GitHub repo.

Contributing

If you wish to contribute a change to this repo, please send a pull request.

Libraries

flutter_segment