UnifyApps Analytics SDK for Flutter
The UnifyApps Analytics SDK is a comprehensive toolkit designed to integrate your Flutter application with the UnifyApps Analytics platform. This SDK empowers developers to track user behavior, monitor app performance, and transmit data securely in real time.
Key Features
- Event Tracking: Record custom and predefined events such as user actions, session data, and errors.
- Real-Time Data Transmission: Send analytics data to UnifyApps Analytics for instant insights.
- Customizable Schema: Define event structures tailored to your application's requirements.
- Secure and Optimized: Enjoy encrypted data communication and performance optimized for Flutter environments.
- Cross-Platform Compatibility: Fully supports Android, iOS, Web, macOS, Windows, and Linux.
Installation for Flutter Applications
Prerequisites
- Flutter SDK installed (version 3.0 or later recommended).
- Dart SDK installed.
Step 1: Install the SDK
Add the dependency in your pubspec.yaml:
dependencies:
unifyapps_sdk_flutter: ^1.0.0
Then run:
flutter pub get
The package is available on pub.dev.
Step 2: Platform-Specific Setup
The package depends on Flutter plugins (shared_preferences, package_info_plus, device_info_plus, and connectivity_plus). Ensure the necessary platform-specific setup described in those packages' documentation is completed.
For Android, add the following permission to android/app/src/main/AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
For iOS, no additional permissions are required by default.
Usage
Step 1: Import the SDK
import 'package:unifyapps_sdk_flutter/analytics_flutter.dart';
Step 2: Initialize the Client
Create an instance of UnifyAppsAnalytics and configure it with the following options:
| Config Option | Type | Description | Default |
|---|---|---|---|
| host | String | Custom host URL for the analytics endpoint | Required |
| apiKey | String | Your API key | Required |
| sessionTimeout | Duration | Session timeout duration | 5 min |
| isEventBatching | bool | Is event batching allowed | true |
| flushAt | int | Number of events in each batch to be sent | 20 |
| flushInterval | Duration | Interval for automatic flushing | 30 seconds |
| heartbeatInterval | Duration | Interval for heartbeat events | 30 seconds |
| debug | bool | To log the payloads and responses | false |
Example:
final analytics = UnifyAppsAnalytics();
Future<void> initAnalytics() async {
await analytics.setup(
host: 'https://www.example.com',
apiKey: 'YOUR_API_KEY',
sessionTimeout: const Duration(minutes: 5),
flushAt: 20,
isEventBatching: true,
debug: false,
);
}
Step 3: Use Analytics in Your App
You can now use the analytics instance throughout your application to track events.
Tracking Methods
The following methods are available to track different user events:
- Track
- Identify
- Screen
- Group
- Alias
- Reset
Methods:
Track
The track method is used to track custom events. You can assign a name to the event and send the properties associated with that event:
await analytics.track(event, properties: properties);
Example: Tracking a form submission. Add the track function in the button's onPressed handler.
import 'package:unifyapps_sdk_flutter/analytics_flutter.dart';
void handleFormSubmit() async {
final formData = {
'userType': 'Guest',
'timestamp': DateTime.now().toIso8601String(),
};
await analytics.track('Form Submission', properties: formData);
// handle form submission ....
}
ElevatedButton(
onPressed: handleFormSubmit,
child: Text('Submit Form'),
)
Identify
The identify method is used to identify a user. It takes userId and userTraits as arguments.
Initially, the user is set to anonymous, and the userId is assigned a randomly generated string.
When calling identify, the user is updated with the new userId and userTraits:
await analytics.identify(userId, traits: userTraits);
Example: Call the identify function after login implementation:
import 'package:unifyapps_sdk_flutter/analytics_flutter.dart';
Future<void> handleLogin() async {
// login implementation...
final userDetails = {
'name': 'John Doe',
'age': 22,
};
await analytics.identify('123', traits: userDetails);
}
Alias
The alias method is used to associate a user with a different ID, allowing you to map multiple IDs to the same user. For example, before logging in, the user is anonymous and is assigned a random ID. After logging in, you can use the alias method to map the anonymous user to the logged-in user:
await analytics.alias(userId);
Example: If you want to link events from before the user logs in (random user id) to those after login (userId), you can create an alias. This event can then be used to map all the activities to one user with different ids.
import 'package:unifyapps_sdk_flutter/analytics_flutter.dart';
Future<void> handleLogin() async {
final userId = '123';
// login implementation...
await analytics.alias(userId);
}
Group
The group method is used to associate a user with a group, such as an organization or company. It takes groupId and groupTraits as arguments:
await analytics.group(groupId, traits: groupTraits);
Example: Adding users organisation details.
import 'package:unifyapps_sdk_flutter/analytics_flutter.dart';
Future<void> setUserOrganization() async {
final organisation = {
'name': 'abc',
'address': 'xyz',
'id': '987',
};
await analytics.group(organisation['id'] as String, traits: organisation);
}
Screen
The screen method is used to track screen views. You can send the screen name along with other related properties:
await analytics.screen(name, properties: properties);
Example: Tracking when the user visits a particular screen:
import 'package:unifyapps_sdk_flutter/analytics_flutter.dart';
import 'package:flutter/material.dart';
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
void initState() {
super.initState();
_trackScreen();
}
Future<void> _trackScreen() async {
final screenDetails = {
'name': 'Home',
'visit': DateTime.now().toIso8601String(),
};
await analytics.screen('Home', properties: screenDetails);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Home screen'),
),
);
}
}
Reset
The reset method is used to reset the analytics state. It sets the user to anonymous and assigns a randomly generated string as the userId:
await analytics.reset();
Example: Clearing User Details after user logouts:
import 'package:unifyapps_sdk_flutter/analytics_flutter.dart';
Future<void> handleLogout() async {
// logout implementation...
await analytics.reset();
}
Flush
The flush method forces pending events to be sent immediately:
await analytics.flush();
Heartbeat
The heartbeat method periodically emits heartbeat events. You can optionally provide a function that returns properties for each heartbeat:
analytics.heartbeat(() => {
return {'customProperty': 'value'};
});
Data Sent
With each event, we also send the context object that contains the following details:
| Property | Description | Example Value |
|---|---|---|
traits |
Object containing user-specific traits. | { name: 'John Doe', email: 'john@example.com' } |
locale |
The user's device language setting. | en-US |
timezone |
The user's current time zone. | America/New_York |
app.name |
The application name. | My Flutter App |
app.version |
The application version. | 1.0.0 |
app.build |
The application build number. | 123 |
app.namespace |
The application package/bundle identifier. | com.example.app |
device.id |
Unique device identifier (when available). | device-uuid |
device.manufacturer |
Device manufacturer. | Apple, Samsung |
device.model |
Device model. | iPhone 14 Pro, SM-G998B |
device.name |
Device name. | John's iPhone |
device.type |
Platform type. | ios, android, web, macos, windows, linux |
device.os.name |
Operating system name and version. | iOS 17.0, Android 14 |
device.os.platform |
Platform identifier. | ios, android, web |
screen.height |
The height of the user's screen in logical pixels. | 1080 |
screen.width |
The width of the user's screen in logical pixels. | 1920 |
screen.density |
The device's screen density (pixel ratio). | 2.0 |
network.cellular |
Whether connected via cellular/mobile data. | true or false |
network.wifi |
Whether connected via WiFi. | true or false |
browser.hostName |
(Web only) The current hostname of the website. | example.com |
browser.userAgent |
(Web only) The browser's user agent string. | Mozilla/5.0... |