Flutter Apps with AWS Amplify Backend: Part 3 — Analytics
Tags: flutter, amplify, aws, s3
Published: 2020-09-10 00:31:55


# Flutter Apps with AWS Amplify Backend: Part 3 — Analytics

How to generate event-driven analytics for your Flutter application

### What is Amplify Analytics
> The Analytics category enables you to collect analytics data for your App. The Analytics category comes with built-in support for [Amazon Pinpoint](https://aws.amazon.com/pinpoint)

**NOTE: Amplify Flutter is still in developer preview and is not recommended for production use at this time.**

![An Amplify Pinpoint Dashboard for our application](https://cdn-images-1.medium.com/max/2350/1*UgKESBF845iAieVT5c_gqQ.png)*An Amplify Pinpoint Dashboard for our application*

### Why you need Analytics

![](https://cdn-images-1.medium.com/max/2000/1*LiLDcSaGMitNmqk0gKivZA.png)

High-quality analytics is a crucial component of any respectable app. They provide insight into how many users are on your app, and more importantly, HOW they are using their app.

Many apps lose users because of a disconnect between what the developer THINKS their users want, and what users ACTUALLY want. By obtaining actual data on how users are interacting with your app, developers can stop ‘developing-blind’.

## Enough Preaching, Let’s Get Started

### Prerequisites

The only thing you need for this tutorial is the app you created in Part 1 of this tutorial series.

If you don’t want to read part 1 and you are already familiar with Amplify Flutter, then simply create a new Flutter application and [connect it to a cloud instance of Amplify.](https://docs.amplify.aws/start/getting-started/setup/q/integration/flutter)

### Create a Basic Amplify Project

If you are using the app you created in Part 1, you can skip this step.

Otherwise, create a new flutter project, and from the project directory run:

    amplify init

### **Setup the Backend**

The backend can be set up entirely through the amplify cli:

    amplify add auth
    amplify add analytics

![Your console should look something like this](https://cdn-images-1.medium.com/max/2714/1*1nIs_2WJ6lqree6k8ORyzw.png)*Your console should look something like this*

As always, run *amplify add push *to push your local changes to the cloud. You should know that enabling analytics will automatically enable authentication (if it hasn’t been added already).

### Integrate the Packages

Add the amplify packages to your **pubspec.yaml.**

    dependencies:
      amplify_core: '<1.0.0'
      amplify_analytics_pinpoint: '<1.0.0'
      amplify_auth_cognito: '<1.0.0'

Next, include the necessary packages in your main.dart file:

    import 'package:amplify_analytics_pinpoint/amplify_analytics_pinpoint.dart';
    import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
    import 'package:amplify_core/amplify_core.dart';

### Initializing Amplify Analytics

I am working hand in hand with the [official documentation ](https://docs.amplify.aws/lib/analytics/getting-started/q/platform/flutter#install-amplify-libraries)to create this application. However, the documentation is actually out of date currently and the suggested code snippets need to be modified before being included in your codebase. In other words: copy-pasting isn’t always your friend.

If you don’t want to be bored with the nitty-gritty of a step by step tutorial, the completed main.dart can be found [here](https://gist.github.com/adamfillion/2e0c7c25fb950a7b214d213313c6b79b). For those of you who want to soldier on with me: let’s dive in.

First, let’s set up a barebones **main.dart** for you to work with:

```dart
import 'package:amplify_analytics_pinpoint/amplify_analytics_pinpoint.dart';
import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
import 'package:amplify_core/amplify_core.dart';

import 'package:flutter/material.dart';

import 'amplifyconfiguration.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

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

class _MyAppState extends State<MyApp> {

  bool _amplifyConfigured = false;

  // Instantiate Amplify
  Amplify amplifyInstance = Amplify();

  @override
  void initState() {
    super.initState();

    // amplify is configured on startup
    _configureAmplify();
  }

  @override
  void dispose() {
    // Clean up the controller when the widget is removed from the

    super.dispose();
  }

  void _configureAmplify() async {
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
```

Your initialization method (called once at app startup) should look something like this:

```dart
  void _configureAmplify() async {
    if (!mounted) return;

    // add all of the plugins we are currently using
    // in our case... just one - Auth
    AmplifyAuthCognito authPlugin = AmplifyAuthCognito();
    AmplifyAnalyticsPinpoint analyticsPlugin = AmplifyAnalyticsPinpoint();

    amplifyInstance.addPlugin(
        authPlugins: [authPlugin], analyticsPlugins: [analyticsPlugin]);

    await amplifyInstance.configure(amplifyconfig);
    try {
      setState(() {
        _amplifyConfigured = true;
      });
    } catch (e) {
      print(e);
    }
  }
```

If you read Part 2 of this series, you will notice that the only change is the new *analyticsPlugin* being added to our *amplifyInstance*. After this step, your application is now ready to log events. Before we do that though, let’s launch your analytics console:

    amplify console analytics

This will launch the analytics console in your browser — a super nice platform for monitoring app activity.

![We haven’t logged any events yet — hence the emptiness.](https://cdn-images-1.medium.com/max/3722/1*xL7ZLtwZUw2bSLQTsvLjyA.png)*We haven’t logged any events yet — hence the emptiness.*

### Logging our First Events

There are many different ways to create events for Amazon Pinpoint. All created events are batched and flushed to the network every 30 seconds by default. If you want to change how often your app sends updates, you can modify the *autoFlushEventsInterval *field in your [amplifyconfiguration.json](https://docs.amplify.aws/lib/analytics/record/q/platform/flutter#flush-events).

To get started, we will create a simple page with a button that logs an event every time it is pressed. Add the following code snippet to your main.dart to implement the simple app.

```dart
  void _createEvent() {
    // simply logs a test event
    AnalyticsEvent event = AnalyticsEvent("test_event");

    event.properties.addBoolProperty("boolKey", true);
    event.properties.addDoubleProperty("doubleKey", 10.0);
    event.properties.addIntProperty("intKey", 10);
    event.properties.addStringProperty("stringKey", "stringValue");

    Amplify.Analytics.recordEvent(event: event);
    Amplify.Analytics.flushEvents();

    print("event logged");
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
          body: Center(
            child: RaisedButton(
              onPressed: _createEvent,
              child: Text("Create Event"),
            ),
          ),
        ));
  }
```

Launch the app. Since we allowed unauthenticated users to send analytics events, we should be able to simply press our *Create Event *button and send events to the Amazon Pinpoint.

![Notice the console messages which indicate successful event transfers](https://cdn-images-1.medium.com/max/2174/1*CoQ3-qE1oFQOTvnAiuCN2Q.png)*Notice the console messages which indicate successful event transfers*

Navigate to your analytics console (via *amplify analytics console)*, and head over to your events dashboard.

![](https://cdn-images-1.medium.com/max/2000/1*387rh2rdfCd1rQu5q-rTog.png)

There, you should see that your dashboard has some new events registered (sometimes it can take a couple of minutes to update).

![In my case… I pressed the button a lot.](https://cdn-images-1.medium.com/max/3206/1*uRFwwwB68uLR86i3_758yQ.png)*In my case… I pressed the button a lot.*

You can filter your events using the filter dropdown. The events can be filtered based on the event type, as well as the event attributes and values. In my experience, **it can take a while for the dashboard to update with the event types and attributes, so be patient.**

![Filtering based on event attributes](https://cdn-images-1.medium.com/max/3226/1*LH2pKecpw9rlrpTfANq0Cg.png)*Filtering based on event attributes*

You can also filter based on the characteristics of the machine that your app is running on. This is particularly useful for identifying which types of phones your users have to create testing plans.

![Endpoint attributes](https://cdn-images-1.medium.com/max/2000/1*IGcj9kBttFahADLwz7cF0Q.png)*Endpoint attributes*

### Adding Custom Endpoint Attributes

Depending on the nature of your application, it may be useful to add custom endpoint attributes if you need more information about your users. For example, perhaps you want to differentiate between different subscription plans of your users. To do that, we can add properties by creating a new *AnalyticsUserProfile:*

```dart

  void _identifyUser() async {
    AnalyticsUserProfile analyticsUserProfile = new AnalyticsUserProfile();
    analyticsUserProfile.name = _userId + "_name";
    analyticsUserProfile.plan = _plan + "_plan";

    Amplify.Analytics.identifyUser(
        userId: _userId, userProfile: analyticsUserProfile);
  }
```


This adds a name and subscription plan to the endpoint’s analytics profile.

I also added some UI to control the *_userId *and *_plan *fields. To see the complete code, head over to the [GitHub repo](https://github.com/Vennify-Inc/flutter-amplify-tutorial/tree/0eb6a26cf09a3ff49f972101a46521ac7d4788ea).

![Add a name and subscription plan, and add them as endpoint properties](https://cdn-images-1.medium.com/max/2000/1*OQfZxSnmiNGqoutFq1xt4g.png)*Add a name and subscription plan, and add them as endpoint properties*

Now, when events are created from this device, they will be accompanied by the endpoint attributes of *{“name”: “jackSparrow”, “plan”: “Premium”}.*

Back in our console, we can now filter based on our new custom attributes.

![Custom.plan and Custom.name are our new custom attributes](https://cdn-images-1.medium.com/max/2014/1*KXbU9COxpc9auuhRx8X1tw.png)*Custom.plan and Custom.name are our new custom attributes*

### Location Data

If you desire location data from your user’s as an endpoint attribute, it can be painlessly added:

```dart
  void _identifyUser() async {
    // adds location data to our analytics profile
    
    AnalyticsUserProfileLocation analyticsUserLocation =
        new AnalyticsUserProfileLocation();
    analyticsUserLocation.latitude = 5;
    analyticsUserLocation.longitude = 5;
    analyticsUserLocation.postalCode = "90210";
    analyticsUserLocation.city = "BeverlyHills";
    analyticsUserLocation.region = "California";
    analyticsUserLocation.country = "USA";

    analyticsUserProfile.location = analyticsUserLocation;

    Amplify.Analytics.identifyUser(
        userId: _userId, userProfile: analyticsUserProfile);
  }
```
## Finishing Up

Congrats on making it this far! If you simply want the completed code from this tutorial, head over to the [GitHub repo](https://github.com/Vennify-Inc/flutter-amplify-tutorial/tree/0eb6a26cf09a3ff49f972101a46521ac7d4788ea). You will still need to perform the Amplify initialization (in fact, you may need to run *amplify delete*) to remove my Amplify folders.

### So… what’s next?

In this tutorial, we simply scratched the surface of what is possible with Amazon Pinpoint in your Flutter application. In future tutorials, we will explore the full array of features that we can leverage to track monetization, leverage AI to issue data-driven recommendations, and foster a deeper understanding of how users are interacting with our app.

Until then, check out my other tutorials in this series to nail down the basics with Amplify for Flutter. Coming up next: [storage.](https://docs.amplify.aws/lib/storage/getting-started/q/platform/flutter)

### This Series

**Part 1:** [Basic Setup](https://medium.com/@vennify.education/flutter-apps-with-aws-backend-part-1-basic-setup-7e1dd53e9161)

**Part 2:** [Authentication](https://medium.com/@vennify.education/flutter-apps-with-aws-backend-part-2-authentication-a66136f23995)

**Part 3:** [Analytics](https://medium.com/@vennify.education/flutter-apps-with-aws-backend-part-3-analytics-bdb8b5bad5c0)

**Part 4:** [Storage](https://medium.com/@vennify.education/flutter-apps-with-aws-backend-part-4-storage-74ae2dbdc4b5)