DEV Community

Cover image for Flutter Apps with AWS Amplify Backend: Part 3 — Analytics
FlutterArticles
FlutterArticles

Posted on • Updated on

Flutter Apps with AWS Amplify Backend: Part 3 — Analytics

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

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

An Amplify Pinpoint Dashboard for our applicationAn Amplify Pinpoint Dashboard for our application

Why you need Analytics

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.

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
Enter fullscreen mode Exit fullscreen mode

Setup the Backend

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

amplify add auth
amplify add analytics
Enter fullscreen mode Exit fullscreen mode

Your console should look something like thisYour 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'
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

Initializing Amplify Analytics

I am working hand in hand with the official documentation 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. 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:

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();
  }
}
Enter fullscreen mode Exit fullscreen mode

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

  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);
    }
  }
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.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.

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.

  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"),
            ),
          ),
        ));
  }
Enter fullscreen mode Exit fullscreen mode

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 transfersNotice the console messages which indicate successful event transfers

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

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.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 attributesFiltering 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 attributesEndpoint 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:


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

    Amplify.Analytics.identifyUser(
        userId: _userId, userProfile: analyticsUserProfile);
  }
Enter fullscreen mode Exit fullscreen mode

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.

Add a name and subscription plan, and add them as endpoint propertiesAdd 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 attributesCustom.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:

  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);
  }
Enter fullscreen mode Exit fullscreen mode

Finishing Up

Congrats on making it this far! If you simply want the completed code from this tutorial, head over to the GitHub repo. 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.

This Series

Part 1: Basic Setup

Part 2: Authentication

Part 3: Analytics

Part 4: Storage

Top comments (0)