Mixpanel Flutter Analytics Integration

mixpanel flutter

Flutter Mixpanel Analytics Integration – Brilliansolution. Mixpanel flutter is a powerful tool that is used to track events, create funnels, see trends and engage users. In this article, we’ll go over how to properly integrate mixpanel into our Flutter app.

Mixpanel Flutter Analytics Integration

STEP 1: Add dependency in your project’s pubspec.yaml file.

device_info_plus: 2.0.1
mixpanel_analytics: 2.0.2
package_info: 2.0.2

To install all these dependencies run the command flutter pub get

STEP 2: Making a function to retrieve device and app information.

Creating DeviceInfo class to collect all the information about the device and app.

mixpanel flutter
mixpanel flutter
class DeviceInfo {
/// [deviceIdentifier] unique identification of device
String deviceIdentifier;

/// [os] iOS or Android
String os;

/// [device] Phone Details - name and model
String device;

/// [appVersion] Current version of the app
String appVersion;

DeviceInfo({
this.deviceIdentifier,
this.os,
this.device,
this.appVersion,
});
}

Creating function for initializing MixPanelAnalyticsManager with app and device details.


void initializingMixPanel() async {
DeviceInfo deviceInfo;

DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
PackageInfo packageInfo = await PackageInfo.fromPlatform(); /// getting device details as per OS
if (Platform.isIOS) {
IosDeviceInfo iosDeviceInfo = await deviceInfoPlugin.iosInfo;
deviceInfo = DeviceInfo(
deviceIdentifier: iosDeviceInfo.identifierForVendor,
os: 'iOS ${iosDeviceInfo.systemName} ${iosDeviceInfo.systemVersion}',
device: '${iosDeviceInfo.name} ${iosDeviceInfo.model}',
appVersion: packageInfo.version,
);
} else {
AndroidDeviceInfo androidDeviceInfo = await deviceInfoPlugin.androidInfo;
deviceInfo = DeviceInfo(
deviceIdentifier: androidDeviceInfo.androidId,
os: 'Android ${androidDeviceInfo.version.release} ${androidDeviceInfo.version.sdkInt}',
device: '${androidDeviceInfo.manufacturer} ${androidDeviceInfo.model}',
appVersion: packageInfo.version,
);
}

/// setting deviceInfo to the MixPanelAnalyticsManager
MixPanelAnalyticsManager.instance.deviceInfo = deviceInfo; /// initializing MixPanelAnalyticsManager
MixPanelAnalyticsManager.init(
mixpanelToken: 'your_mixpanel_token',
deviceInfo: deviceInfo,
);
}

STEP 3: Creating singleton class for MixPanelAnalyticsManager

class MixPanelAnalyticsManager {
static MixPanelAnalyticsManager _instance;
static final _user$ = StreamController<String>.broadcast();
MixpanelAnalytics _mixpanelAnalytics;
DeviceInfo _deviceInfo;
String _mixpanelToken;

/// factory instance to setup MixPanelAnalyticsManager
factory MixPanelAnalyticsManager.init({String mixpanelToken, DeviceInfo deviceInfo}) { /// skipping initialization for FlutterWeb and for Test mode.
if (kIsWeb || !Platform.environment.containsKey('FLUTTER_TEST')) {
_instance ??= MixPanelAnalyticsManager._(mixpanelToken, deviceInfo);
}
return MixPanelAnalyticsManager();
}

/// creating a dummy object for the cases when the instance has not been created
/// this way instance can't be null

MixPanelAnalyticsManager();

/// Private init method for implementing singleton class
MixPanelAnalyticsManager._(this._mixpanelToken, this._deviceInfo) {
_mixpanelAnalytics = MixpanelAnalytics.batch(
/// [token] is the Mixpanel token associated with your project.

token: _mixpanelToken,

/// [userId$] is a stream which contains the value of the userId that will be used to identify the events for a user.

userId$: _user$.stream,

/// [uploadInterval] is the interval used to batch the events.

uploadInterval: Duration(seconds: 30),

/// [shouldAnonymize] will anonymize the sensitive information (userId) sent to mixpanel.

shouldAnonymize: false,

/// [shaFn] function used to anonymize the data.

shaFn: (value) => value,

/// [verbose] true will provide a detailed error cause in case the request is not successful.

verbose: !kReleaseMode,

/// Mixpanel will use the ip address of the incoming request
useIp: true,
);

/// adding user Identifier as deviceIdentifier which will be unique
_user$
.add(_deviceInfo.deviceIdentifier);
}

static MixPanelAnalyticsManager get instance {
return _instance ?? MixPanelAnalyticsManager();
}

/// converting [DeviceInfo] into map
Map<String, String> get metaData {
return {
'deviceIdentifier': _deviceInfo.deviceIdentifier,
'os': _deviceInfo.os,
'device': _deviceInfo.device,
'appVersion': _deviceInfo.appVersion,
};
}

/// setter function to update DeviceInfo
set deviceInfo(DeviceInfo value) {
_deviceInfo = value;
}

/// function for initializing user in mixpanel
void sendUserProperties(String name) async {
if (name.isNotEmpty && _instance != null && _mixpanelAnalytics != null) {
await _mixpanelAnalytics.engage(
operation: MixpanelUpdateOperations.$set,
value: {
'\$name': '$name',
'Device ID': metaData['deviceIdentifier'],
'OS': metaData['os'],
'Device': metaData['device'],
'App Version': metaData['appVersion'],
},
);
}
}

/// function for sending event in mixpanel
void sendEvent({
@required String eventName,
Map<String, Object> properties,
}) async {
if (_instance != null && _mixpanelAnalytics != null) {
properties ??= {};

/// adding all DeviceInfo properties to existing properties
properties.addAll(
{
'Device ID': metaData['deviceIdentifier'],
'OS': metaData['os'],
'Device': metaData['device'],
'App Version': metaData['appVersion'],
},
);
await _mixpanelAnalytics.track(
event: eventName,
properties: properties,
);
}
}
}

STEP 4: Sending an event with MixPanelAnalyticsManager.

Calling initializingMixPanel in the app’s main method.

void main() {
initializingMixPanel();
runApp(MyApp());
}

Set user in initState method of your very first screen of the app.

@override
void initState() {
super.initState();
MixPanelAnalyticsManager.instance.sendUserProperties('Flutter');
}

By adding the eventName and your custom properties as a map, you can send an event to the mixpanel.

MixPanelAnalyticsManager.instance.sendEvent(
eventName: 'API',
properties: {
'api_endpoint': '/get_user_details',
'status': 200,
'screen_called_from': 'HomeScreen',
},
);

In the example above, we are sending an API status event from HomeScreen. You can send anything to track any type of event because the developer has authority over the properties map.

So that’s it for the time being, I’ll be back with another interesting and important article. Happy Fluttering!

If you find this article useful, please do hit the clap icon 👏 and share it with your friends, as it will motivate me to write more.

Feel free to connect with me on social media platforms for any doubts regarding Flutter.

Keywords :

  • Mixpanel Flutter Analytics Integration
  • Mixpanel
  • Flutter

brillian

Leave a Reply

%d bloggers like this: