☀︎ Languages: English | Persian (فارسی) 🇮🇷
WiseTrack Flutter Plugin
The WiseTrack Flutter plugin offers a cross-platform solution to accelerate your app’s growth — helping you increase users, boost revenue, and reduce costs, all at once.
Table of Contents
- Features
- Requirements
- Installation
- Initialization
- Basic Usage
- Advanced Usage
- Example Project
- Breaking Changes
- Troubleshooting
- License
Features
- Cross-platform tracking for iOS, Android, and Web
- Support for custom and revenue event logging
- Push notification token management (APNs and FCM)
- App Tracking Transparency (ATT) support for iOS
- Configurable logging levels
- Advertising ID retrieval (IDFA for iOS, Ad ID for Android)
- Web platform support with JavaScript interop integration
- Unified API across all platforms (mobile and web)
Requirements
- Flutter 2.0.0 or later
- Dart 2.12.0 or later
- iOS 11.0 or later
- Android embedding v2 enabled
- Android API 21 (Lollipop) or later
- Android Gradle Plugin >= 7.1.0 for full compatibility with Java 17
Installation
To integrate the WiseTrack Flutter Plugin into your Flutter project, follow these steps:
-
Add the dependency: Add the
wisetrackplugin to yourpubspec.yamlfile:dependencies: wisetrack: ^2.2.0 # Replace with the latest version -
Install the package: Run the following command in your project directory:
flutter pub get -
Configure iOS: To support App Tracking Transparency (ATT) on iOS, add the following key to your
ios/Runner/Info.plist:<key>NSUserTrackingUsageDescription</key> <string>We use this data to provide a better user experience and personalized ads.</string> -
Configure Android: Ensure your
android/app/build.gradlehas the following settings:android { compileSdkVersion 33 defaultConfig { minSdkVersion 21 targetSdkVersion 33 } }Android Permissions: To enable the WiseTrack SDK to access device information and network features on Android, add the following permissions to your
android/app/src/main/AndroidManifest.xml:<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />If your app does not target the Google Play Store (e.g., CafeBazaar, Myket), add these additional permissions:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" />Feature-Specific Dependencies (Android): The WiseTrack SDK supports additional Android features that require specific dependencies. Add only the dependencies for the features you need in
android/app/build.gradle:-
Google Advertising ID (Ad ID): Enables retrieval of the Google Advertising ID via
getAdId().implementation 'com.google.android.gms:play-services-ads-identifier:18.2.0' -
Open Advertising ID (OAID): Enables OAID as an alternative to Ad ID for devices without Google Play Services (e.g., Chinese devices) via
WTInitialConfigwithoaidEnabled: true.implementation 'io.wisetrack.sdk:oaid:2.0.0' // Replace with the latest version -
Huawei Ads Identifier: Enables Ad ID retrieval on Huawei devices. add repository:
maven { url 'https://developer.huawei.com/repo/' }and this dependency:
implementation 'com.huawei.hms:ads-identifier:3.4.62.300'-
Referrer Tracking: Enables referrer tracking for Google Play and CafeBazaar via
WTInitialConfigwithreferrerEnabled: true.implementation 'io.wisetrack.sdk:referrer:2.0.0' // Replace with the latest version implementation 'com.android.installreferrer:installreferrer:2.2' // Google Play referrer implementation 'com.github.cafebazaar:referrersdk:1.0.2' // CafeBazaar referrer -
Firebase Installation ID (FID): Enables retrieval of a unique Firebase Installation ID for device identification.
implementation 'com.google.firebase:firebase-installations:17.2.0'To use Firebase services, register your app in the Firebase Console:
- Add your package name (e.g.,
com.example.app). - Download the
google-services.jsonfile and place it inandroid/app/. - Update
android/build.gradle:buildscript { dependencies { classpath 'com.google.gms:google-services:4.4.1' // Or latest version } } - Apply the Google Services plugin in
android/app/build.gradle:apply plugin: 'com.google.gms.google-services'
- Add your package name (e.g.,
-
AppSet ID: Provides additional device identification for analytics.
implementation 'com.google.android.gms:play-services-appset:16.1.0'
-
-
Rebuild the project: Run your project to ensure all dependencies are correctly integrated:
flutter run
Initialization
To start using the WiseTrack Flutter Plugin, initialize it with a configuration object in your app's entry point (e.g., main.dart).
Example
import 'package:flutter/material.dart';
import 'package:wisetrack/wisetrack.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialize WiseTrack
final config = WTInitialConfig(
appToken: 'your-app-token',
webAppVersion: kIsWeb ? '1.0.0' : null, // Required for web platform
userEnvironment: WTUserEnvironment.production, // Use .sandbox for testing
androidStore: WTAndroidStore.playstore,
iOSStore: WTIOSStore.appstore,
logLevel: WTLogLevel.warning,
);
await WiseTrack.instance.init(config);
runApp(MyApp());
}
Note: Replace 'your-app-token' with the token provided by the WiseTrack dashboard.
Basic Usage
Below are common tasks you can perform with the WiseTrack Flutter Plugin.
Enabling/Disabling Tracking
Enable or disable tracking at runtime:
// Enable tracking
await WiseTrack.instance.setEnabled(true);
// Disable tracking
await WiseTrack.instance.setEnabled(false);
// Check if tracking is enabled
bool isTrackingEnabled = await WiseTrack.instance.isEnabled();
print('Tracking enabled: $isTrackingEnabled');
Requesting App Tracking Transparency (ATT) Permission (iOS)
For iOS 14+, request user permission for tracking:
bool isAuthorized = await WiseTrack.instance.iOSRequestForATT();
print('Tracking Authorized: $isAuthorized');
Starting/Stopping Tracking
Manually control tracking:
// Start tracking
await WiseTrack.instance.startTracking();
// Stop tracking
await WiseTrack.instance.stopTracking();
Uninstall Detection and Setting Push Notification Tokens
To enable WiseTrack Uninstall Detection feature, you need to configure your project to receive push notifications using Firebase Cloud Messaging (FCM). NOTE: For a working implementation, you can check the example project
1. Configure Firebase Cloud Messaging (FCM)
Follow the official FlutterFire documentation to set up FCM in your project: 👉 Firebase Cloud Messaging Setup Guide
Ensure that:
- Your app is registered in the Firebase Console.
- The
google-services.json(Android) orGoogleService-Info.plist(iOS) files are added correctly. - Firebase dependencies (
firebase_coreandfirebase_messaging) are added and initialized in your project.
2. Handle Notification Tokens
Once FCM is configured, you need to get Fcm and APNS token and pass them to WiseTrack:
static _getToken() async {
final token = await FirebaseMessaging.instance.getToken();
if (token != null) {
WiseTrack.instance.setFCMToken(token);
}
final apnsToken = await FirebaseMessaging.instance.getAPNSToken();
if (apnsToken != null) WiseTrack.instance.setAPNSToken(apnsToken);
FirebaseMessaging.instance.onTokenRefresh.listen((token) {
WiseTrack.instance.setFCMToken(token);
});
}
3. Handle Incoming Notifications
And finally inside your FirebaseMessaging.onMessage or FirebaseMessaging.onBackgroundMessage handlers, call the following helper method to check if the message belongs to WiseTrack:
// For handle notification when app is in foreground:
FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
if (await WiseTrack.instance.isWiseTrackNotification(message.data)) {
// This notification is handled internally by WiseTrack.
return;
}
// Otherwise, handle your app's custom notifications here.
});
// For handle notification when app is in background or terminated:
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
if (await WiseTrack.instance.isWiseTrackNotification(message.data)) {
// This notification is handled internally by WiseTrack.
return;
}
// Otherwise, handle your app's custom notifications here.
}
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
4. Enable Background Modes & Background Task Identifier for iOS App
To improve uninstall detection reliability, your app must support Background Fetch and Background Processing. You can enable them in two ways:
-
Using Xcode Capabilities tab: Go to your project target (Runner App) → Signing & Capabilities → Background Modes and enable:
- Background fetch
- Background processing
-
Manually via
Info.plist: Add the following keys:<key>UIBackgroundModes</key> <array> <string>fetch</string> <string>processing</string> </array>Add the WiseTrack task identifier to your
ios/Runner/Info.plist<key>BGTaskSchedulerPermittedIdentifiers</key> <array> <string>io.wisetrack.sdk.bgtask</string> </array>
Logging Custom Events
Log custom or revenue events:
// Log a default event
await WiseTrack.instance.logEvent(WTEvent(
name: 'Custom Event',
params: {
'key-str': 'value',
'key-num': 1.1,
'key-bool': true,
},
));
// Log a revenue event
await WiseTrack.instance.logEvent(WTEvent.revenue(
name: 'Purchase',
currency: 'USD',
amount: 9.99,
params: {
'item': 'Premium Subscription',
},
));
Note: Event parameter keys and values have a maximum limit of 50 characters.
Setting Log Levels
Control the verbosity of SDK logs:
await WiseTrack.instance.setLogLevel(WTLogLevel.debug); // Options: none, error, warning, info, debug
Retrieving Advertising IDs
Retrieve the Identifier for Advertising (IDFA) on iOS or Advertising ID (Ad ID) on Android:
// Get IDFA (iOS)
String? idfa = await WiseTrack.instance.getIdfa();
print('IDFA: ${idfa ?? "Not available"}');
// Get Ad ID (Android)
String? adId = await WiseTrack.instance.getAdId();
print('Ad ID: ${adId ?? "Not available"}');
Note: On web platform, advertising ID retrieval is not supported due to browser privacy restrictions. These methods will return null on web.
Advanced Usaged
Customizing SDK Behavior
You can customize the SDK behavior through the WTInitialConfig parameters:
General Parameters:
appToken: Your unique app token (required).userEnvironment: The environment (.production,.sandbox).trackingWaitingTime: Delay before starting tracking (in seconds).startTrackerAutomatically: Whether to start tracking automatically.customDeviceId: A custom device identifier.defaultTracker: A default tracker for event attribution.logLevel: Set the initial log level.attributionDeeplink: Indicates whether attribution via deep links is enabled.eventBuffering: Enables event buffering to optimize data transmission.appSecret: The secret key used for authentication or encryption purposes.secretId: A unique secret identifier linked to the app's credentials.
Mobile-Specific Parameters:
androidStore: The Android app store (e.g.,.googleplay,.cafebazaar,.other, ...).iOSStore: The iOS app store (e.g.,.appstore,.sibche,.other, ..).oaidEnabled: Indicates whether the Open Advertising ID (OAID) is enabled.referrerEnabled: Indicates whether the Referrer ID is enabled.
Web-Specific Parameters:
webAppVersion: The app version for web (required for web platform).
Example with Advanced Configuration:
final config = WTInitialConfig(
appToken: 'your-app-token',
// Web-specific (required when targeting web)
webAppVersion: kIsWeb ? '1.0.0' : null,
userEnvironment: WTUserEnvironment.sandbox,
androidStore: WTAndroidStore.googlePlay,
iOSStore: WTIOSStore.appStore,
trackingWaitingTime: 5,
startTrackerAutomatically: true,
customDeviceId: 'custom-device-123',
defaultTracker: 'default-tracker',
logLevel: WTLogLevel.debug,
oaidEnabled: false,
referrerEnabled: true,
);
await WiseTrack.instance.init(config);
WebView Integration
The WebView Integration feature allows you to bridge communication between JavaScript running inside a WebView and your Flutter application using the WiseTrackWebBridge system.
This is especially useful when embedding a web-based user interface or a hybrid web app in your Flutter application and you need to:
- Call native features from JavaScript (like
logEvent,initialize,getIDFA, etc.) - Receive asynchronous responses back from Flutter/Dart to your JS code
WiseTrack supports integration with the two most popular Flutter WebView packages:
Integration with webview_flutter
- Create JSEvaluator:
class FlutterWebViewJSEvaluator implements WiseTrackJsEvaluator {
final WebViewController controller;
FlutterWebViewJSEvaluator(this.controller);
@override
void addJSChannelHandler(String name, JSMessageCallback messageCallback) {
controller.addJavaScriptChannel(
name,
onMessageReceived: (message) => messageCallback(message.message),
);
}
@override
Future<void> evaluateJS(String script) {
return controller.runJavaScript(script);
}
@override
void removeJSChannelHandler(String name) {
controller.removeJavaScriptChannel(name);
}
}
- Create and Register
WiseTrackWebBridge:
final _controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted);
// Initialize WebBridge with flutter webview evaluator
final webBridge = WiseTrackWebBridge(
evaluator: FlutterWebViewJSEvaluator(_controller),
);
webBridge.register();
_controller.loadRequest(...);
Note: register WiseTrackWebBridge before load any content in webview controller!
Integration with flutter_inappwebview
- Create JSEvaluator:
class InAppWebViewJSEvaluator implements WiseTrackJsEvaluator {
final InAppWebViewController controller;
InAppWebViewJSEvaluator(this.controller);
@override
void addJSChannelHandler(String name, JSMessageCallback messageCallback) {
controller.addJavaScriptHandler(
handlerName: name,
callback: (messages) => messageCallback(messages.first),
);
}
@override
Future<void> evaluateJS(String script) {
return controller.evaluateJavascript(source: script);
}
@override
void removeJSChannelHandler(String name) {
controller.removeJavaScriptHandler(handlerName: name);
}
}
- Create and Register
WiseTrackWebBridge:
InAppWebView(
...
onWebViewCreated: (controller) {
// Initialize WebBridge with inapp webview evaluator
webBridge = WiseTrackWebBridge(
evaluator: InAppWebViewJSEvaluator(controller));
webBridge.register();
},
....
)
Helper Files (.js files)
These JavaScript files are provided to help you build and test web pages intended for display inside the WebView. You can use them as a reference or foundation when integrating WiseTrack functionality into your in-app HTML pages.
Located in: assets
Files include:
wisetrack.js: Main interface for invoking bridge methods.wt_config.js: Contains theWTInitConfigconstructor and configuration schema.wt_event.js: Defines theWTEventstructure for event logging.test.html: A standalone page to manually trigger SDK methods via a UI or console.
Example Project
An example project demonstrating the WiseTrack Flutter Plugin integration is available at GitHub Repository URL. Clone the repository and follow the setup instructions to see the plugin in action.
Breaking Changes
Version 2.2.0
-
Method Rename:
enableTestMode()has been renamed toclearAndStop()// OLD (Version 2.1.x and earlier) await WiseTrack.instance.enableTestMode(); // NEW (Version 2.2.0+) await WiseTrack.instance.clearAndStop(); -
Default Environment Change: The default
userEnvironmenthas changed fromWTUserEnvironment.sandboxtoWTUserEnvironment.production// Explicitly set sandbox if needed final config = WTInitialConfig( appToken: 'your-app-token', userEnvironment: WTUserEnvironment.sandbox, // Explicitly set sandbox ); -
Web Platform Requirement:
webAppVersionparameter is now required when targeting web platform// Add webAppVersion for web builds final config = WTInitialConfig( appToken: 'your-app-token', webAppVersion: kIsWeb ? '1.0.0' : null, // Required for web );
Troubleshooting
- SDK not initializing: Ensure the
appTokenis correct and the network is reachable. - Logs not appearing: Set the log level to
WTLogLevel.debugand ensure a log listener is set up:WiseTrack.instance.listenOnLogs((message) => print('SDK Log: $message')); - IDFA/Ad ID not available: Ensure ATT permission is granted (iOS) or Google Play Services is included (Android).
- Web initialization fails: Ensure
webAppVersionis provided inWTInitialConfig - Web events not tracking: Check browser console for JavaScript errors and enable web-specific logging
For further assistance, contact support at [email protected].
License
The WiseTrack Flutter Plugin is licensed under the WiseTrack SDK License Agreement. See the LICENSE file for details.