Flutter数据分析与跟踪插件growingio_flutter_plugin的使用

Flutter数据分析与跟踪插件growingio_flutter_plugin的使用

添加依赖

在 Flutter 项目的 pubspec.yaml 文件中 dependencies 里面添加 growingio_flutter_plugin 依赖。

dependencies:
  growingio_flutter_plugin: '^4.0.0'

然后执行 flutter pub get 指令安装插件。

Flutter 插件初始化

GrowingIO Flutter SDK 需要在 Flutter 中初始化 SDK。

Flutter 初始化

在 Flutter 端进行初始化,推荐将 SDK 的初始化代码放入 main.dartmain 中,代码示例如下:

void main() async {
  /// 代码中的 <ProjectId>、<DataSourceId>、<UrlScheme>请自行替换为自己项目的对应值。
  var option = AutotrackerConfiguration("<ProjectId>", "<DataSourceId>", "<UrlScheme>");
  option.dataCollectServerHost = "https://napi.growingio.com";
  option.debugEnabled = false;
  option.dataCollectionEnable = true;
  option.androidConfig = AndroidConfiguration(
      channel: "应用宝", androidIdEnabled: true, imeiEnabled: false, requireAppProcessesEnabled: true);
      
  option.addGioComponent(EncoderLibraryGioModule());

  /// 设置完配置后,调用该接口进行初始化
  GrowingAutotracker.startWithConfiguration(option);

  runApp(MyApp());
}

初始化配置说明

在 Flutter 初始化中会传入各式的参数,AutotrackerConfiguration 参数配置如下表所示:

配置项 参数类型 是否必填 默认值 说明 版本
projectId String null 项目ID,每个应用对应唯一值 -
dataSourceId String null 应用的DataSourceId,唯一值 -
urlScheme String null 应用特有的URLScheme,用于外部应用拉起应用,如圈选 -
dataCollectionServerHost String null 服务端部署后的 ServerHost -
autoTrackAllRoutePage bool true 是否自动开启页面采集 -
debugEnabled bool false 调试模式,会打印SDK log,抛出错误异常,在线上环境请关闭 -
cellularDataLimit int 10 每天发送数据的流量限制,单位MB -
dataUploadInterval int 15 数据发送的间隔,单位秒 -
sessionInterval int 30 会话后台留存时长,单位秒 -
dataCollectionEnabled bool true 是否采集数据 -
requestTimeout int 30 设置数据上报请求的超时时间,单位秒 -
dataValidityPeriod int 7 设置为上报数据在数据库的缓存时间,单位天 -
idMappingEnabled bool false 是否开启多用户身份上报 -
autotrackAllRoutePage bool true 设置是否发送 Route 页面上的Page事件 -
autotrackEnabled bool true 设置原生端是否打开无埋点功能 -
autotrackAllNativePage bool false 设置原生端是否自动发送Page事件 -
modules Set<LibraryGioModule> empty 模块集成,具体请阅读下方的模块说明 -
androidConfig AndroidConfiguration null 用于配置Android设备上特有的一些属性 -
iosConfig IosConfiguration null 用于配置iOS设备上特有的一些属性 -

AndroidConfiguration 参数特有配置如下表所示:

配置项 参数类型 是否必填 默认值 说明 版本
channel String null Android 应用的分发渠道 -
androidIdEnabled bool false 是否允许在 Android 设备上采集 AndroidId -
imeiEnabled bool false 是否允许在 Android 设备上采集 imei -
requireAppProcessesEnabled bool false 是否允许在 Android 设备上获取应用进程名称 -

IosConfiguration 目前暂无特有配置。

URL Scheme 配置说明

在使用 GrowingIO SDK 的 Mobile Debugger 和圈选功能时,用于外部浏览器通过扫描二维码来拉起应用。

模块配置

GrowingIO SDK 利用模块来实现SDK核心功能以外的额外功能,在 Flutter SDK 插件中,可以通过在 modules 传入模块声明来开启相应的功能。

广告功能

option.addGioComponent(AdsLibraryGioModule(
    config: AdsConfig(
        readClipBoardEnable: true,
        asaEnabled: true,
        deepLinkHost: "https://ads-uat.growingio.cn",
        deepLinkCallback: (Map params, int error, int time) {
          print("deeplink params: $params");
        })));

加密模块

option.addGioComponent(EncoderLibraryGioModule());

Json 模块

option.addGioComponent(JsonLibraryModule());

API说明

GrowingAutotracker.getContext().setDataCollectionEnabled(true)
GrowingAutotracker.getContext().setLoginUserId(userId: "cpacm",userKey: "name")
GrowingAutotracker.getContext().cleanLoginUserId()
GrowingAutotracker.getContext().setLoginUserAttributes(attributes: {"sex":"female"});
GrowingAutotracker.getContext().setLocation(latitude: 20.11,longitude: 20.11)
GrowingAutotracker.getContext().cleanLocation()
GrowingAutotracker.getContext().getDeviceId()
GrowingAutotracker.getContext().trackCustomEvent(eventName: "eventName", attributes: {"age":"18"})
String? timerId =await GrowingAutotracker.getContext().trackTimerStart(eventName: "custom");
GrowingAutotracker.getContext().trackTimerPause(timerId: timerId!);
GrowingAutotracker.getContext().trackTimerResume(timerId: timerId);
GrowingAutotracker.getContext().trackTimerEnd(timerId: timerId,attributes: {});
GrowingAutotracker.getContext().removeTimer(timerId: timerId);
GrowingAutotracker.getContext().clearTrackTimer();
GrowingAutotracker.getContext().setGeneralProps(props:{});
GrowingAutotracker.getContext().removeGeneralProps(keys:["col1 row1", "key1"]);
GrowingAutotracker.getContext().clearGeneralProps();

GrowingAutotracker.getContext().registerComponent(module);

1. 数据采集开关

setDataCollectionEnabled

打开或关闭数据采集

参数说明
参数 参数类型 说明
enabled boolean true 打开数据采集,false 关闭数据采集,默认 true
示例
GrowingAutotracker.getContext().setDataCollectionEnabled(true);

2. 设置登录用户ID

setLoginUserId

当用户登录之后调用,设置登录用户ID

参数说明
参数 参数类型 说明
userId String 长度限制大于0且小于等于1000,如果大于长度1000将只截取前1000长度
userKey String 适用于ID-MAPPING,可设置 userId 的类型,可选填
示例
GrowingAutotracker.getContext().setLoginUserId(userId: "cpacm",userKey: "name");

3. 清除登录用户ID

cleanLoginUserId

当用户登出之后调用,清除已经设置的登录用户ID。

示例
GrowingAutotracker.getContext().cleanLoginUserId();

4. 设置用户的地理位置

setLocation

设置用户当前的地理位置,基于WGS-84坐标

参数说明
参数 参数类型 说明
latitude double 地理坐标点纬度
longitude double 地理坐标点经度
示例
GrowingAutotracker.getContext().setLocation(latitude: 20.11,longitude: 20.11);

5. 清除用户的地理位置

cleanLocation

清除用户当前的地理位置

示例
GrowingAutotracker.getContext().cleanLocation();

6. 设置登录用户属性

setLoginUserAttributes

发送登录用户属性事件,用于用户信息相关分析; 在添加发送用户属性事件代码之前,需在CDP平台用户管理界面创建用户属性。

参数说明
参数 参数类型 说明
attributes Map<String, String> 用户属性信息
示例
GrowingAutotracker.getContext().setLoginUserAttributes(attributes: {"sex":"female"});

7. 设置埋点事件

trackCustomEvent

发送一个埋点事件;注意:在添加发送的埋点事件代码之前,需在CDP平台事件管理界面创建埋点事件以及关联事件属性;

如果事件属性需关联维度表,请在事件属性下关联维度表( CDP平台版本>= 2.1 )

参数说明
参数 参数类型 说明
eventName String 事件名,事件标识符
attributes Map<String, String> 事件发生时所伴随的属性信息;当事件属性关联有维度表时,属性值为对应的维度表模型ID(记录ID)(可选)
示例
GrowingAutotracker.getContext().trackCustomEvent(eventName: "custom",attributes: {"item":"exp"});

8. 获取设备ID

getDeviceId

获取设备ID,又称为匿名用户ID,SDK 自动生成用来定义唯一设备。 如果没有初始化SDK 或者关闭采集开关可能返回值为null,且可能有IO操作。

示例
GrowingAutotracker.getContext().getDeviceId();

9. 事件化计时器

trackTimerStart

初始化一个事件计时器,参数为计时事件的事件名称,返回值为该事件计时器唯一标识

trackTimerPause

暂停事件计时器,参数为trackTimerStart返回的唯一标识

trackTimerResume

恢复事件计时器,参数为trackTimerStart返回的唯一标识

trackTimerEnd

停止事件计时器,参数为trackTimerStart返回的唯一标识。调用该接口会自动触发删除定时器。

removeTimer

删除事件计时器,参数为 trackTimerStart 返回的唯一标识。 该接口会将标识为 timerId 的计时器置为空。调用停止计时器接口,会自动触发该接口。注意移除时不论计时器处于什么状态,都不会发送事件。

clearTrackTimer

清除所有已经注册的事件计时器。 存在所有计时器需要清除时调用。注意移除时不论计时器处于什么状态,都不会发送事件。

参数说明
参数 参数类型 说明
eventName String 事件名称,事件标识符
attributes Map<String, String> 事件发生时所伴随的属性信息
返回值说明
参数 参数类型 说明
timerId String 计时器唯一标识
示例
String? timerId =await GrowingAutotracker.getContext().trackTimerStart(eventName: "custom");
GrowingAutotracker.getContext().trackTimerPause(timerId: timerId!);
GrowingAutotracker.getContext().trackTimerResume(timerId: timerId);
GrowingAutotracker.getContext().trackTimerEnd(timerId: timerId,attributes: {});
GrowingAutotracker.getContext().removeTimer(timerId: timerId);
GrowingAutotracker.getContext().clearTrackTimer();

10. 通用属性

setGeneralProps({required Map<String, dynamic> props})

为所有的自定义事件(CustomEvent)添加通用属性。

removeGeneralProps({required List<String> keys})

根据Key值移除已经设置的属性,如不存在则不影响。

clearGeneralProps()

清除所有已经设置的通用属性。

示例
GrowingAutotracker.getContext().setGeneralProps(props:{"key1":"name"});
GrowingAutotracker.getContext().removeGeneralProps(keys:["xxx", "key1"]);
GrowingAutotracker.getContext().clearGeneralProps();

11. 注册模块组件

registerComponent

可通过该方法手动注册SDK需要的可配置模块组件(推荐在初始化通过 Configuration 初始化时注册)。

参数说明
参数 参数类型 说明
module LibraryGioModule 模块
config Configuration 模块的配置类(可选参数)
示例
GrowingAutotracker.getContext().registerComponent(JsonLibraryModule());

12. 无埋点页面事件

Flutter的 Page事件可以通过 mixin 类 GrowingPageStateMixin 或者 GrowingPageStatelessMixin 来手动实现。

  1. StatefulWidget 中,可以将其 State 声明为 Page页面,如下:
class _HomeScreenState extends State<HomeScreen> with GrowingPageStateMixin {
  [@override](/user/override)
  String get alias => "HomeScreen";

  [@override](/user/override)
  Map<String, dynamic>? get attributes => {};
}
  1. StatelessWidget 中,直接将自己声明为 Page 页面,如下:
class SplashScreen extends StatelessWidget with GrowingPageStatelessMixin {
  [@override](/user/override)
  String get alias => "SplashScreen";

  [@override](/user/override)
  Map<String, dynamic>? get attributes => {};
}

更多关于Flutter数据分析与跟踪插件growingio_flutter_plugin的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据分析与跟踪插件growingio_flutter_plugin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


growingio_flutter_plugin 是一个用于在 Flutter 应用中集成 GrowingIO 数据分析与跟踪功能的插件。GrowingIO 是一个用户行为分析平台,可以帮助开发者跟踪用户行为、分析用户路径、优化产品体验等。

1. 安装插件

首先,你需要在 pubspec.yaml 文件中添加 growingio_flutter_plugin 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  growingio_flutter_plugin: ^latest_version

然后运行 flutter pub get 来安装插件。

2. 初始化插件

在你的 Flutter 应用中初始化 GrowingIO 插件。通常在 main.dart 文件中进行初始化:

import 'package:flutter/material.dart';
import 'package:growingio_flutter_plugin/growingio_flutter_plugin.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化 GrowingIO
  GrowingIO growingIO = GrowingIO();
  await growingIO.start('your_project_id', 'your_url_scheme');

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

3. 配置 Android 和 iOS 项目

Android

android/app/build.gradle 文件中,确保已经启用了 FlutterPluginAndroidLifecycle

android {
    ...
    defaultConfig {
        ...
        multiDexEnabled true
    }
    ...
}

AndroidManifest.xml 文件中,添加以下权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

iOS

ios/Runner/Info.plist 文件中,添加以下配置:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

4. 设置用户属性

你可以通过 setUserAttributes 方法来设置用户属性:

GrowingIO growingIO = GrowingIO();
growingIO.setUserAttributes({
  'user_id': '123456',
  'name': 'John Doe',
  'email': 'john.doe@example.com'
});

5. 跟踪事件

你可以通过 track 方法来跟踪自定义事件:

GrowingIO growingIO = GrowingIO();
growingIO.track('purchase', {
  'item': 'product_id_123',
  'price': 99.99,
  'quantity': 1
});

6. 页面跟踪

插件会自动跟踪页面切换,但你也可以手动调用 trackPage 方法来跟踪特定页面:

GrowingIO growingIO = GrowingIO();
growingIO.trackPage('HomePage');

7. 用户标识

你可以通过 setUserId 方法来设置用户标识:

GrowingIO growingIO = GrowingIO();
growingIO.setUserId('user_id_123');

8. 清除用户信息

你可以通过 clearUserId 方法来清除用户信息:

GrowingIO growingIO = GrowingIO();
growingIO.clearUserId();

9. 调试模式

你可以通过 setDebugMode 方法来启用调试模式:

GrowingIO growingIO = GrowingIO();
growingIO.setDebugMode(true);
回到顶部