AWS Amplify For Flutter Part 6: Amplify Analytics

AWS Amplify For Flutter Part 6: Amplify Analytics

The last of the series, this article explores how to integrate analytics feats on Amplify and implement them for our projects

ยท

6 min read

In this article, we shall explore the various analytics features that are offered by Amplify and also see how we can implement them in our Flutter applications. Amplify Analytics category will allow you to collect useful analytics data of your app as well as of the application's users. This category has been built on top of Amazon Pinpoint and Amazon Kinesis. We will cover the Amazon Pinpoint section of analytics in this read up as Amazon Kinesis is not yet available for Flutter.

What will we cover in this article?

  • Setting up Amplify Analytics in Flutter project
  • Recording events for analytics
  • Track sessions in your app
  • Identify users for analysis
  • Use existing AWS resources in Amplify

Setting up Amplify Analytics in your Flutter project

Setting up Analytics is as simple as adding any other feature from Amplify. The best way to go forward is to take help from Amplify CLI and add the relevant package to initialize it and you are pretty good to go.

To go forward, you need to configure Amplify CLI and integrate it with your project. If you need help with this, you can refer Part 1 of the series.

Setting up Analytics with CLI

  • To start off, you need to run the following command in your project's root directory:
amplify add analytics
  • Amplify will ask you a few questions, you can refer to the below code to configure the analytics:
? Select an Analytics provider (Use arrow keys)
    `Amazon Pinpoint`
? Provide your pinpoint resource name: 
    `yourPinpointResourceName`
? Apps need the authorization to send analytics events. Do you want to allow guests and unauthenticated users to send analytics events? (we recommend you allow this when getting started) 
    `Yes`
  • Once you are done with this, the only thing that is left to do is push the configuration to Amplify by running amplify push.
  • After the setup, you will notice that your amplifyconfiguration.dart is updated with references provided for Amplify Pinpoint. Now we can move forward by adding the Pinpoint package and initialising it.
  • Next, open your pubspec.yaml file and add the amplify_analytics_pinpoint package as shown below:
environment:
  sdk: ">=2.11.0 <3.0.0"

dependencies:

  # Should already be added during Project Setup walkthrough 
  amplify_flutter: '<1.0.0'

  # Add these lines in `dependencies` 
  amplify_analytics_pinpoint: '<1.0.0'
  • To initialise, just add AmplifyAnalyticsPinpoint() when you callAmplify.addPlugins. The code snippet for your reference is given below:
import 'package:amplify_flutter/amplify.dart';
import 'package:amplify_analytics_pinpoint/amplify_analytics_pinpoint.dart';
import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';

import 'amplifyconfiguration.dart';

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
    @override
    void initState() {
        super.initState();
        _configureAmplify();
    }

    void _configureAmplify() async {
        // Add the following line to add Pinpoint and Cognito plugin to your app
        Amplify.addPlugins([AmplifyAuthCognito(), AmplifyAnalyticsPinpoint()]);

        try {
            await Amplify.configure(amplifyconfig);
        } on AmplifyAlreadyConfiguredException {
            print("Tried to reconfigure Amplify; this can occur when your app restarts on Android.");
        }
    }
}

Recording events for analytics

  • Recording an analytical event is very simple and straightforward when you use a Amplify Analytics package. You have to create an object for AnalyticsEvent with any event name and call the relevant property function to record the event. Event supports boolean, integer, double and string data types for calling events. The code snippet for your reference is given below:
AnalyticsEvent event = AnalyticsEvent('SomeTitle');
event.properties.addStringProperty('Hello', 'World'); 
event.properties.addBoolProperty('Successful', true);
event.properties.addIntProperty('ProcessDuration', 792); 
event.properties.addDoubleProperty('doubleKey', 120.3);

Amplify.Analytics.recordEvent(event: event);
  • This plugin is quite smart and is capable of handling the scenario if you retry to login. Amplify Analytics batches the event updates and calls instead of sending data for each event which considerably reduces the network bandwidth used. By default, all events flushes or sends the component after every 30 seconds. But, this can easily be modified in amplifyconfiguration.dart by changing the value of the autoFlushEventsInterval to your desired interval in milliseconds. Use the code given below:
{
    "UserAgent": "aws-amplify-cli/2.0",
    "Version": "1.0",
    "analytics": {
        "plugins": {
            "awsPinpointAnalyticsPlugin": {
                "pinpointAnalytics": {
                    "appId": "AppID",
                    "region": "Region"
                },
                "pinpointTargeting": {
                    "region": "Region"
                },
                "autoFlushEventsInterval": 10000
            }
        }
    }
}
  • There might be some cases when you want to override the flush event and do a forced flush. In such cases, you can use the flushEvent() function as shown below:
Amplify.Analytics.flushEvents();
  • You can also can also set global properties to your events using the following code:
AnalyticsProperties properties = new AnalyticsProperties();
properties.addStringProperty('AppStyle', 'DarkMode'); 
Amplify.Analytics.registerGlobalProperties(globalProperties: properties);
  • If you wish to remove the global properties, you have to call the unregisterGlobalProperties() function. You can also enable and disable collection for your analytical event by using the following methods:
Amplify.Analytics.enable();

Amplify.Analytics.disable();

Track sessions on your app

Pinpoint will, by default, track the app session in the background and send that data as a batch to AWS. You can view this data from the Pinpoint console. To open the console quickly, you can use Amplify CLI, as shown:

amplify console analytics
  • On the console, choose Analytics from the left panel and then select Event.
  • Select the Enable Filter to see when the event commences and concludes.

Identify users for analysis

Pinpoint allows you to capture analytical data for users by sending information related to logged-in users or guest users to Amazon Pinpoint. For collecting a user's data you need to get the ID from the Amplify authorisation package. In case your app has location access, you can send the location using AnalyticsUserProfileLocation as shown:


AnalyticsUserProfileLocation location = new AnalyticsUserProfileLocation();
    location.latitude = 32.423424;
    location.longitude = -52.342342;
    location.postalCode = '98122';
    location.city = 'Seattle';
    location.region = 'WA';
    location.country = 'USA';

AnalyticsProperties properties = new AnalyticsProperties();
    properties.addStringProperty('phoneNumber', '+11234567890'); 
    properties.addIntProperty('age', 25); 

AnalyticsUserProfile userProfile = new AnalyticsUserProfile();
    userProfile.name = username;
    userProfile.email = 'name@example.com';
    userProfile.location = location; 

Amplify.Analytics.identifyUser(userId: userId, userProfile: profile);

Use existing AWS resources in Amplify

If you already have Pinpoint service on an existing project and just want to use that in your app, then you need Application ID and Region from the Pinpoint console. Add the following code in your amplifyconfiguration.json for the desired result:

{
    "analytics": {
        "plugins": {
            "awsPinpointAnalyticsPlugin": {
                "pinpointAnalytics": {
                    "appId": "[APP ID]",
                    "region": "[REGION]"
                },
                "pinpointTargeting": {
                    "region": "[REGION]"
                }
            }
        }
    }
}

pinpointAnalytics take two parameters -

  • appId - The application ID fr AWS Pinpoint can be found in the Pinpoint console.
  • region - The AWS Region where in which Pinpoint is provisioned.

People mostly use Pinpoint for marketing strategies and other similar scenarios. But, there are a lot of things you can do with AWS Pinpoint like connecting with customers via emails, SMS, push notifications, voice calls, etc.

Conclusion

Using Analytics in your app helps developers in making data-driven decisions and judgments about user experience and content as well as smart design decisions. Till now, we have covered almost all the features currently supported by Amplify for Flutter, i.e., Authentication, APIs, Storage, DataStore, and Analytics through these series. There are some features that are not supported by Amplify for Flutter like, Pub/Sub, AI/ML Predictions, interactions and push notifications which I shall write about as soon as they are officially supported.

This is the last part of the AWS Amplify for Flutter series. It was quite a journey and thank you for sticking through till the end. If you find this article useful, then you can give a ๐Ÿ‘ to this article and come say hi on Twitter.

ย