Flutter
Getting Started
1. Install
- Add the following lines to your package's pubspec.yaml file to include the dependency:
dependencies:
percept_flutter: ^1.2.0
- To install the package, use the following command in your command line interface:
$ flutter pub get
- Import the package in your Dart code to make it available for use:
import 'package:percept_flutter/percept_flutter.dart'
2. Initialize Percept SDK
import 'package:percept_flutter/percept_flutter.dart'
class YourClassState extends State<YourClass> {
Percept percept;
@override
void initState() {
super.initState();
percept=Percept(token)
}
}
Percept constructor takes some optional parameters which are as follows:
Parameter Name | Description | Default Value |
---|---|---|
autoCaptureAppLifecycleEvents | Auto track app life cycle events or not | true |
autoCaptureUnhandledErrors | Auto track unhandled errors | true |
maxBatchSize | Default batch size of event requests | 100 |
maxDelayMins | Maximum interval between retry requests in case of failure | 30 min |
maxCacheSizeMb | Maximum cache size used to store failed requests | 10 mb |
clearAfterDays | Days after which stored failed requests are deleted in case of retry failure | 7 days |
enableExperiment | Enables or disables the experiment feature within the service | false |
experimentFetchedCb | A callback function that is triggered when experiment data is fetched | undefined |
experimentRefetchIntervalMin | The interval, in minutes, at which the experiment data is refetched | undefined |
int maxBatchSize = 100, int maxDelayMins = 30, int maxCacheSizeMb = 10, int clearAfterDays = 7
NOTE: Token is the percept workspace token associated with your app.
3. Set user
After successfully initializing the SDK, On login set current User using the following function.
percept.setUser(userId: "userId",userProperties: {UserProperty.name:"TestUser"}, additionalProperties: {"isVerifiedAccount": true})
4. Set currrent user properties
use setCurrentUserProperties
method to set properties on the user profile created by setUser
// first call this method
await percept.setUser(userId: 'U1');
// sets user `deviceToken` and `isPaidUser` property to true
percept.setCurrentUserProperties(userProperties: {UserProperty.deviceToken:"token"}, additionalProperties: {"isPaidUser": true})
UserProperties can only have keys present in the UserProperty enum which are as follows.
User Property Name | Description |
---|---|
userId | UserId associated with the user |
name | name of the user |
phone | Phone number associated with the user |
Email ID associated with the user | |
deviceToken | FCM token for the device |
To get your firebase token you can use:
FirebaseMessaging.instance.getToken()
or
FirebaseMessaging.instance.onTokenRefresh.listen((token) => { });
5. Engage
Integration with Firebase Messaging: To streamline push notification functionality and accurately monitor their impact on attribution.
- Capture when app session is initiated from terminated state by interacting with push notification.
// Get any messages which caused the application to open from a terminated state.
RemoteMessage? initialMessage = await FirebaseMessaging.instance.getInitialMessage();
if (initialMessage != null) {
_percept.trackPNTerminated(initialMessage.toMap());
}
- Capture when app session is resumed from background state by interacting with push notification.
// Get any messages which caused the application to open from a terminated state.
FirebaseMessaging.onMessageOpenedApp.listen(
(message) => _percept.trackPNBackground(message.toMap()),
);
- Capture when the app was in foreground and the push notification was received.
// Get any messages which were received when the app was in foreground.
FirebaseMessaging.onMessage.listen(
(message) => _percept.trackPNForeground(message.toMap()),
);
- Notifying SDK when notification received in terminated state for better attribution
Register the handler before calling runApp. Details for background fcm message handling-> https://firebase.google.com/docs/cloud-messaging/flutter/receive#background_messages
import 'package:percept_flutter/constants.dart';
import 'package:percept_flutter/utils/comm_helpers.dart';
@pragma('vm:entry-point')
Future<void> bgMessageHandler(RemoteMessage message) async {
CapturePerceptCommRequest(
PerceptCommunicationState.received, message.toMap(), PERCEPT_TEST_KEY);
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultOptions.currentPlatform);
FirebaseMessaging.onBackgroundMessage(bgMessageHandler);
runApp(MyApp());
}
This property will be tracked by pi_pn_attribution property in every subsequently tracked event.
pi_pn_attribution | Description |
---|---|
terminated | Interaction with pn initiated current app session from terminated state |
background | Interaction with pn resumed current app session from background state |
foreground | Notification was received when the app was in foreground state |
none | Current session is not attributed to any pn |
Along with pi_pn_attribution property following properties are tracked:
Property_name | Description |
---|---|
pi_pn_targetUrl | TargetUrl in the notification payload |
pi_pn_campaignId | CampaignId associated with the notificaiton |
pi_pn_campaignName | CampaignName associated with the notificaiton |
pi_pn_campaignSource | CampaignSource associated with the notificaiton |
Note: It is essential to have Firebase Messaging implemented to enable support for these properties.
6. Send Event
You can capture event using the following function. Percept automatically generates a unique ID and stores it in local storage or a cookie.
// Track only event-name
percept.capture('Referral Banner Click');
// Track event-name with property
percept.capture('Screen View', {'screenName': 'Homepage'});
// Track handled errors
percept.captureError(error, stackTrace);
After initializing the library, Percept will automatically track some properties by default
7. Set Global Properties
Set global properties which will be passed with all subsequent events
percept.setGlobalProperties({'global-property-key', 'value'});
8. Get all global properties
Get all global properties
percept.getGlobalProperties();
9. Clear
Call clear function on logout to delete all user related information
percept.clear()