Skip to Content
AI Powered Docs! 🤖 These docs are translated with AI, so keep an eye out for minor quirks. We're always improving!
Technical DocumentationFlutterFlutter SDK Implementation

pub package


You can view the sample Metrix implementation project for Flutter here .


Adding the Metrix Library to Your Project

Add the Metrix plugin dependency to your project’s pubspec.yaml file and then run the flutter pub get command.

dependencies: metrix_analytics: ^2.8.0

Setting Up the Library in the Application

Depending on your application’s target platform, follow the steps below to enable it:


Setup for Android Application

  1. Place the Metrix application ID (app id) and API key (api key) in your application’s AndroidManifest.xml file:
<manifest> ... ```xml <application> ... <!-- Add the following lines and replace YOUR_APP_ID --> <meta-data android:name="ir.metrix.APPLICATION_ID" android:value="YOUR_APP_ID" /> <!-- Add the following lines and replace YOUR_API_KEY --> <meta-data android:name="ir.metrix.API_KEY" android:value="YOUR_API_KEY" /> </application>

YOUR_APP_ID: Your application ID obtained from the Metrix panel.

YOUR_API_KEY: Your API key obtained from the Metrix panel.

Note: The AndroidManifest.xml file is located in the path android -> app -> src -> main.

Enhancing Library Security

You should increase the security of communication and data transfer, as well as ensure greater integrity of your application’s statistics, by enabling the SDK signature feature in your panel and obtaining your specific identifier.

After enabling SDK Signature in your panel, retrieve the corresponding signature identifier from the Encoded column and place it in your application file as follows:

Metrix.setSignature("YOUR_SIGNATURE");

Note: Ensure this permission is included in the project’s final merged manifest.

<manifest> <uses-permission android:name="com.google.android.gms.permission.AD_ID"/> ... </manifest>

Features and Capabilities


Event

Any interaction a user has with your application can be defined as an event in your panel and application, allowing the Metrix library to provide you with related statistical data.

In the Metrix library, two types of events can be defined:

  • Custom: Depending on your application’s logic and user interactions, you can create and send your custom events in the format described below.
  • Revenue: A specific type of custom event related to revenue generated within your application, containing a measurable financial value.

Creating a Custom Event

To create a custom event, first register your desired event in the “Event Management” section of your panel and use its slug as the event name in the application.

The event occurrence can be recorded in two ways:

  1. Recording the event using only the slug defined in the panel:
Metrix.newEvent("my_event_slug");
  1. Recording the event using a custom name: (In this case, an event with a unique slug will be automatically created in the panel)
Metrix.newEventByName("my_event_name");

Note: Events can be registered with any number of associated attributes:

For example, suppose you want to create a custom event in an online shopping application:

Map<String, Object> attributes = new Map(); attributes["first_name"] = "Ali"; attributes["last_name"] = "Bagheri"; attributes["manufacturer"] = "Nike"; attributes["product_name"] = "shirt"; attributes["type"] = "sport"; attributes["size"] = "large"; attributes["purchase_date"] = "2024-11-20T11:24:03.000Z"; // use ISO 8601 to consider this attribute as a date Metrix.newEvent("purchase_event_slug", attributes); Metrix.newEventByName("purchase_event_name", attributes);

The parameters for the newEvent method in this case are as follows:

  • First parameter: The slug of your desired event as defined in the Metrix panel.
  • Second parameter: A Map<String, Object> that specifies the event’s attributes.

Creating a Revenue Event

Using this function, you can create a revenue event. To do this, first register your desired event in the “Event Management” section of your panel and use its slug as the event name in the application.

Metrix.newRevenue("my_event_slug", 12000, currency: 0);

The parameters for the newRevenue method are as follows:

  • First parameter: The slug of your desired event as defined in the Metrix panel.
  • Second parameter: A numeric value representing the revenue amount.
  • Third parameter: Specifies the currency used and can take one of three values: 0 (Rial) (default), 1 (Dollar), or 3 (Euro).

Alternatively, you can call the revenue event using a custom name (In this case, an event with a unique slug will be automatically created in the panel):

Metrix.newRevenueByName("my_event_name", 12000, currency: 0);

Identifying Users to Metrix and Creating a User (Specific to Automation Service)

To identify a user who is using your website to Metrix’s servers—so that Metrix can determine which user is performing the received actions—you must call the following method before invoking any other methods. This method creates a User on Metrix’s servers, which can be accessed through the Metrix user panel in the User Lookup section.

Metrix.setUserCustomId('userId'); // call when user tries to login in your system and set userId value that user already knows in your system Metrix.deleteUserCustomId(); // call when your user goes to logout in your system

Updating User Information (Specific to Automation Service)

Using the following methods, you can update the information of existing Users in the User Lookup section.

Map<String, Object> attributes = new Map(); attributes["manufacturer"] = "Nike"; attributes["birth_date"] = "2024-11-20T11:24:03.000Z"; // use ISO 8601 to consider this attribute as a date Metrix.addUserAttributes(attributes);

Using the following functions, you can assign predefined Attributes to the user:

Metrix.setUserFirstName('userFirstName'); Metrix.setUserLastName('userLastName'); Metrix.setUserPhoneNumber('phoneNumber'); Metrix.setUserHashedPhoneNumber('hashedPhoneNumber'); Metrix.setUserEmail('email'); Metrix.setUserHashedEmail('hashedEmail'); Metrix.setUserCountry('country'); Metrix.setUserCity('city'); Metrix.setUserRegion('region'); Metrix.setUserLocality('locality'); Metrix.setUserGender(gender); // gender value could be "MALE" , "FEMALE" or "OTHER" Metrix.setUserBirthday(birthday); // birthday value type should be 'Long' timestamp Metrix.userChannelEnabled(channel); // channel value could be "SMS", "PUSH" or "EMAIL" Metrix.userChannelDisabled(channel); // channel value could be "SMS", "PUSH" or "EMAIL"

Note: Each event can have up to 50 attributes, with a maximum length of 512 bytes for each key and value.


Retrieving Metrix Device Identifiers

For each device that installs your application, Metrix generates a unique identifier that you can retrieve as soon as it is identified. To access this identifier, use the method:

Metrix.getUserId().listen((id) => { // TODO });

Note: The Metrix identifier will be available to you once the device has been identified by the Metrix service.


Session

Every interaction a user has with an application occurs within a session. The Metrix library collects information about the user’s various sessions in your application and their durations, making it available to you.

Session Identifier

The Metrix library generates a unique identifier for each session, which you can retrieve. To obtain this identifier, call the following method:

Metrix.setSessionIdListener().listen((id) => { // TODO });

Current Session Number

Using the following method, you can track the user’s current session number throughout their entire usage of your application:

Metrix.setSessionNumberListener().listen((sessionNum) => { // TODO });

Uninstall Tracking

Metrix uses silent push notifications to track when your application is uninstalled.

To use this feature, you must utilize Firebase Cloud Messaging (FCM).


Follow these steps:

  • Enter Push Credentials for the Firebase project in the Metrix panel

Go to your application settings in the Metrix panel and select the Uninstall Config tab.
Enter your Firebase project settings in the relevant fields and click the Save button to store the values.

To obtain the Service Account Data file, go to your Firebase console, navigate to Project Settings, select the Service Accounts tab, and click Generate New Private Key.

push configuration


  • Activating Uninstall Tracking

After entering the settings in the Metrix panel, enable uninstall tracking by turning on the corresponding toggle.


  • Sending Push Token in the Application

After implementing FCM in your application, when you receive the push notification token, send this token to Metrix by calling the following method:

Metrix.setPushToken(token);

Retrieving Campaign Information

Using the following method, you can retrieve the information of the advertising campaign you have set in your tracker within the panel.

Metrix.getAttributionData().listen((metrixAttribution) => { // TODO });

The metrixAttribution model provides you with the following information:

metrixAttribution.acquisitionAd // Ad name metrixAttribution.acquisitionAdSet // Ad group metrixAttribution.acquisitionCampaign // Advertising campaign metrixAttribution.acquisitionSource // Advertising network metrixAttribution.acquisitionSubId // Ad subgroup metrixAttribution.attributionStatus // Indicates the user's status in the campaign

The value of AttributionStatus includes one of the following:

  • ATTRIBUTED - Attributed
  • NOT_ATTRIBUTED_YET - Not yet attributed
  • ATTRIBUTION_NOT_NEEDED - Attribution not needed
  • UNKNOWN - Unknown status

Deep Linking in Android Applications

If you use trackers with deep linking enabled, you can receive the deep link URL and its content. The device responds based on whether the application is installed (standard scenario) or not installed (deferred scenario). If your application is installed, the deep link information is sent to your application.

The Android platform does not automatically support the deferred scenario. In this case, Metrix has its own specific scenario to deliver deep link information to the application.

Standard Scenario

To implement the standard scenario, you can use the uni_links  package.

Deferred Scenario

This scenario occurs when a user clicks on a deep link but does not have your application installed on their device at the time of clicking. In this case, after clicking, the user is redirected to Google Play to install your application. Upon installation, during the first launch, the deep link information is passed to the application.

If you wish to handle the deferred scenario, you can use the following callback:

Metrix.shouldLaunchDeeplink = true; Metrix.getDeeplinkResponse().then((deeplink) => { // TODO });

After Metrix retrieves the deep link information from its server, it passes the content to the above callback. If the shouldLaunchDeeplink value is true, Metrix automatically executes the standard scenario; otherwise, Metrix only provides the information in this callback for you to perform your desired action based on it.

Note: The deferred scenario can only be executed if the application is installed via the Google Play Store.


Setting a Default Tracker

You can assign a tracker to users whose installation does not result from a click. To do this, you need to place the identifier of the tracker you defined in the panel within the application.

This feature is useful when you intend to distribute your APK file directly and want to track the installation statistics from this distribution separately in Metrix.

Note: Under no circumstances should you publish your application on the store with a default tracker. Doing so will cause all your organic installations to be counted under that tracker in Metrix.


Activation for Android Application


Place the tracker identifier in your application’s AndroidManifest.xml file as follows:

<manifest> ... <application> ... <!-- Add the following lines and replace with the identifier --> <meta-data android:name="metrix_trackerToken" android:value="TOKEN" /> </application> </manifest>

Differentiating Organic Installs by Store

If you want to publish your application on different stores such as Cafe Bazaar, Google Play, etc., you can track which store (e.g., Cafe Bazaar, Google Play, Myket, Bazaar, website, etc.) the user installed the application from and identify the sources of your organic installs.

To do this, you need to create separate builds for your application for publication on different stores and configure the corresponding store name in each build.


Activation for Android Application


Place the store name in your application’s AndroidManifest.xml file as follows:

<manifest> ... <application> ... <!-- Add the following lines and replace with the store name --> <meta-data android:name="metrix_storeName" android:value="STORE_NAME" /> </application> </manifest>

Push Notification Service Implementation

  • To begin, download the google-services.json file from the Firebase console and place it in your project.

  • It is also necessary to enter the Firebase project’s Push Credentials in the Metrix panel.

In the Metrix panel, go to your application settings and select the App Push tab under Channel Integration. On this page, enter your Firebase project settings in the relevant fields and click the Save button to store the values.

To obtain the Service Account Data file, go to your Firebase console, navigate to Project Settings, select the Service Accounts tab, and click Generate New Private Key.

push configuration

Then:

  1. Add the following code to your Android application’s gradle.properties file:
metrix.notification.enable=true
  1. Place the following values in your application’s AndroidManifest.xml file:
<service android:name="ir.metrix.notification.receivers.MetrixFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>

Note: Currently, push notifications are only available for identified users in Metrix. To enable this, the user must have the customUserId attribute set.

  1. Set the customUserId when the user logs in and remove it when they log out:
Metrix.setUserCustomId('yourCustomUserId');
Metrix.deleteUserCustomId();

Implementing In-App Messages

By default, the application loads and displays messages every time it is opened.

To show messages on your desired screen:

  1. Set the value of metrix_auto_load_in_app_messages in your application’s AndroidManifest.xml file:
<manifest> ... <application> ... <meta-data android:name="metrix_auto_load_in_app_messages" android:value="false" /> </application> </manifest>
  1. Then, call the following method in the desired location:
Metrix.loadInAppMessages();