flutter_analytics 1.2.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 82

Flutter Analytics #

A barebones Analytics SDK to collect anonymous metadata from flutter apps.

Installation #

Add dependency to pubspec.yaml:

dependencies:
  ...
  flutter_analytics: ^1.2.0

Run in your terminal:

flutter packages get

Usage #

import 'package:flutter_analytics/flutter_analytics.dart' show Analytics;

// initial setup to run once on application lifecycle
Analytics.setup(destinations: ['http://localhost:3000/analytics']);

// uniquely identify group of users
Analytics.group('someGroupId', {'numTrait': 7, 'txtTrait': 'tGroup'});

// uniquely identify current user and its traits
Analytics.identify('anUserId', {'numTrait': 5, 'txtTrait': 'uUser'});

// identify current screen being viewed
Analytics.screen('My Screen', {'numProp': -1, 'txtProp': 'pScreen'});

// track discrete events
Analytics.track('Any Event', {'numProp': 3, 'txtProp': 'pTrack'});

Server-side consumption example #

Receive batches of flutter_analytics on AWS Lambda and ship them to S3:

from base64 import b64decode
from boto3 import client
from datetime import datetime
from dateutil.parser import parse
from gzip import GzipFile
from io import BytesIO
from json import dumps, loads
from zlib import decompress, MAX_WBITS

s3 = client('s3')

bucket = 'my.bucket'
output_file = 'output.json'

def lambda_handler(event, context):
  try:
    return {'statusCode': 200, 'body': upload(event)}
  except Exception as e:
    return {'statusCode': 500, 'body': str(e)}


def upload(event):
  decoded = b64decode(loads(event['body'])['batch'])

  batch = loads(decompress(decoded, MAX_WBITS | 16))

  gz_body = BytesIO()

  gz = GzipFile(None, 'wb', 1, gz_body)
  gz.write(dumps(batch).encode('utf-8'))
  gz.close()

  s3.put_object(
    Body=gz_body.getvalue(),
    Bucket=bucket,
    Key=output_file,
    ContentEncoding='gzip',
    ContentType='application/json'
  )

  return '{"success":true}'

OTA remote configuration #

A remote config file can be supplied like this:

Analytics.setup(
  configUrl: 'https://gist.githubusercontent.com/oakromulo/7678b2b187a24e47c0ba93085575477d/raw/e72767273e4e6a73d14377f650be63d66033a6e3/config.json'
)

Run the example on a simulator #

cd ~/flutter_analytics/example
flutter packages get
open -a simulator
flutter run

Run integration tests #

cd ~/flutter_analytics/test
flutter packages get
APP_CONFIG_URL="https://remote.config" dart tool/tool_env.dart
flutter drive --target=lib/main.dart

Build documentation locally #

cd ~/flutter_analytics
rm -rf doc
dartdoc
serve doc/api
open 'localhost:5000'

License #

MIT

v1.2.0 - 2019-10-24

v1.1.1+1 - 2019-10-18

  • update connectivity dependency

v1.1.1 - 2019-10-18

  • Dependencies and environment constraints updated

v1.1.0 - 2019-10-17

  • Non-persistent payload pointers added for chronological debugging purposes
  • README updated with examples for server-side analytics consumption and OTA config

v1.0.0 - 2019-10-16

  • Full analytics refactor for improved codebase clarity
  • Leverages the latest flutter_persistent_queue implementation under the hood
  • JSON-encodable <dynamic> payloads now supported
  • Improved settings and localstorage caching
  • Better debugging messages on debug targets and saner error handling throughout

v0.4.1 - 2019-10-03

  • Improve persistency of groupId and userId

v0.4.0 - 2019-09-26

  • Implicit cast of DateTime props within payloads to ISOStrings

v0.3.5 - 2019-09-25

  • Improved debugging and error handling

v0.3.4+1 - 2019-09-17

  • Minor maintenance

v0.3.4 - 2019-09-16

  • Updated dependencies

v0.3.3 - 2019-06-17

  • Improved documentation

v0.3.2 - 2019-06-17

  • Improved example

v0.3.1 - 2019-06-17

  • First public release

example/lib/main.dart

// ignore_for_file: unawaited_futures, public_member_api_docs
import 'package:flutter/material.dart';
import 'package:flutter_analytics/flutter_analytics.dart';

Future<void> example() async {
  // initial setup to run once on application lifecycle
  Analytics.setup(destinations: ['http://localhost:3000/analytics']);

  // uniquely identify group of users
  Analytics.group('someGroupId', {'numTrait': 7, 'txtTrait': 'tGroup'});

  // uniquely identify current user and its traits
  Analytics.identify('anUserId', {'numTrait': 5, 'txtTrait': 'uUser'});

  // identify current screen being viewed
  Analytics.screen('My Screen', {'numProp': -1, 'txtProp': 'pScreen'});

  // track discrete events
  Analytics.track('Any Event', {'numProp': 3, 'txtProp': 'pTrack'});

  // debug logged events to console (returning `true` bypasses `destinations`)
  Analytics.flush((batch) async {
    batch.forEach(print);

    return true;
  });
}

Future<String> runExample() async {
  try {
    await example();

    return 'Everything fine, see console!';
  } catch (e, s) {
    debugPrint('$e\n$s');

    return 'Something went wrong, see console!';
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: runExample(),
      builder: (context, snapshot) {
        return MaterialApp(
          home: Scaffold(
            body: Center(
              child: Text(snapshot.data.toString() ?? 'hold on'),
            ),
          ),
        );
      }, // builder
    );
  } // build
}

void main() => runApp(MyApp());

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_analytics: ^1.2.0

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_analytics/flutter_analytics.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
64
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
82
Learn more about scoring.

We analyzed this package on Nov 21, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.6.1
  • pana: 0.12.21
  • Flutter: 1.9.1+hotfix.6

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.3.0 <3.0.0
connectivity ^0.4.5+1 0.4.5+3
device_info ^0.4.1 0.4.1+1
devicelocale ^0.2.0 0.2.0
flutter 0.0.0
flutter_persistent_queue ^5.1.0 5.1.0
flutter_udid ^1.0.1 1.0.1
http ^0.12.0+2 0.12.0+2
localstorage ^3.0.0+2 3.0.1+4
package_info ^0.4.0+9 0.4.0+10
path_provider ^1.4.0 1.4.4
uuid ^2.0.2 2.0.4
Transitive dependencies
async 2.4.0
charcode 1.1.2
collection 1.14.11 1.14.12
convert 2.1.1
crypto 2.1.3
http_parser 3.1.3
meta 1.1.7 1.1.8
path 1.6.4
pedantic 1.8.0+1
platform 2.2.1
sky_engine 0.0.99
source_span 1.5.5
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_driver
test any