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

发布于 1周前 作者 songsunli 来自 Flutter

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

Tealium Flutter Plugin

Tealium Flutter 插件用于在Flutter应用中集成Tealium的数据分析和用户行为跟踪功能。以下是一个完整的示例代码,展示了如何使用Tealium Flutter插件进行数据分析和跟踪。

import 'dart:math';
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:tealium/common.dart';
import 'package:tealium/tealium.dart';
import 'package:tealium_example/tealium_button.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  static final visitorIdentityKey = "visitor_identity";
  final traceIdValue = TextEditingController();
  final userIdValue = TextEditingController();
  String result = '';
  String currentVisitorId = '';

  // MARK: Tealium Configuration

  var config = TealiumConfig(
      'tealiummobile',
      'demo',
      TealiumEnvironment.dev,
      [Collectors.AppData, Collectors.Lifecycle],
      [Dispatchers.RemoteCommands, Dispatchers.Collect],
      consentPolicy: ConsentPolicy.GDPR,
      useRemoteLibrarySettings: true,
      batchingEnabled: false,
      visitorServiceEnabled: true,
      consentExpiry: ConsentExpiry(5, TimeUnit.MINUTES),
      visitorIdentityKey: visitorIdentityKey);

  [@override](/user/override)
  void initState() {
    // MARK: Initialize Tealium
    Tealium.initialize(config).then((value) {
      developer.log('Tealium Initialized');
      Tealium.setConsentStatus(ConsentStatus.consented);
      Tealium.setConsentExpiryListener(() {
        developer.log('Consent Expired');
      });
      Tealium.setVisitorServiceListener((profile) {
        _logVisitorProfile(profile);
      });
      Tealium.getVisitorId().then((value) {
        _logVisitorId(value);
      });
      Tealium.setVisitorIdListener((visitorId) {
        _logVisitorId(visitorId);
      });
      Tealium.addCustomRemoteCommand('json-test', (payload) {
        _logRemoteCommand('JSON Test', payload);
      });
      Tealium.getFromDataLayer(visitorIdentityKey)
          .then((value) {
            setState(() {
              userIdValue.text = value;
            });
          });
    });
    super.initState();
  }

  ListView _listView() {
    return new ListView(
      scrollDirection: Axis.vertical,
      padding: EdgeInsets.all(5),
      children: [
        TextField(
          controller: traceIdValue,
          autocorrect: true,
          decoration: InputDecoration(hintText: 'Enter Trace Id'),
        ),
        TealiumButton(
          title: 'Join Trace',
          onPressed: _joinTrace,
        ),
        TealiumButton(
          title: 'Leave Trace',
          onPressed: () {
            Tealium.leaveTrace();
          },
        ),
        TealiumButton(
          title: 'Track Event',
          onPressed: () {
            Tealium.track(TealiumEvent('Some Event', {'button_click': 'test'}));
          },
        ),
        TealiumButton(
          title: 'Track View',
          onPressed: () {
            Tealium.track(TealiumView('Some View', {'screen_view': 'tester'}));
          },
        ),
        TealiumButton(
          title: 'Add Data',
          onPressed: () {
            Tealium.addToDataLayer({'hello': 'world'}, Expiry.session);
          },
        ),
        TealiumButton(
          title: 'Get Data',
          onPressed: () {
            Tealium.getFromDataLayer('hello').then((value) {
              developer.log('Value From Data Layer: $value');
            });
          },
        ),
        TealiumButton(
          title: 'Remove Data',
          onPressed: () {
            Tealium.removeFromDataLayer(['hello']);
          },
        ),
        TealiumButton(
          title: 'Set Consent',
          onPressed: () {
            Tealium.setConsentStatus(ConsentStatus.consented);
          },
        ),
        TealiumButton(
          title: 'Get Consent',
          onPressed: () {
            Tealium.getConsentStatus()
                .then((status) {
                  developer.log('Consent Status: $status');
                });
          },
        ),
        TealiumButton(
          title: 'Set Consent Categories',
          onPressed: () {
            _setRandomConsentCategories();
          },
        ),
        TealiumButton(
          title: 'Get Consent Categories',
          onPressed: () {
            Tealium.getConsentCategories().then((categories) {
              developer.log('Consent Categories: ' + categories.join(","));
            });
          },
        ),
        TealiumButton(
          title: 'Add Remote Command',
          onPressed: () {
            Tealium.addCustomRemoteCommand('example', (payload) {
              _logRemoteCommand('Example', payload);
            });
          },
        ),
        TealiumButton(
          title: 'Remove Remote Command',
          onPressed: () {
            Tealium.removeRemoteCommand('json-test');
          },
        ),
        TealiumButton(
          title: 'Get Visitor Id',
          onPressed: () {
            Tealium.getVisitorId().then((visitorId) {
              developer.log('Visitor Id: $visitorId');
            });
          },
        ),
        TealiumButton(
          title: 'Gather Track Data',
          onPressed: () {
            Tealium.gatherTrackData().then((data) {
              developer.log('Gather track Data: $data');
            });
          },
        ),
        TealiumButton(
          title: 'Terminate Tealium',
          onPressed: () {
            Tealium.terminateInstance();
          },
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('Identity:'),
            Padding(padding: EdgeInsets.all(3)),
            Expanded(
              child: TextField(
                controller: userIdValue,
                autocorrect: true,
                decoration: InputDecoration(hintText: 'Enter an Identity'),
              ),
            ),
          ],
        ),
        Padding(
          padding: EdgeInsets.symmetric(vertical: 10),
          child: Text('Current Visitor ID: $currentVisitorId',
              textAlign: TextAlign.center),
        ),
        TealiumButton(
          title: 'Set Identity',
          onPressed: _setIdentity,
        ),
        TealiumButton(
          title: 'Reset Visitor Id',
          onPressed: () {
            Tealium.resetVisitorId();
          },
        ),
        TealiumButton(
          title: 'Clear Stored Visitor Ids',
          onPressed: () {
            Tealium.clearStoredVisitorIds();
          },
        ),
      ],
    );
  }

  void _logVisitorProfile(dynamic profile) {
    var encodedData = json.encode(profile);
    var converted = json.decode(encodedData);
    developer.log('=========Visitor Service Response=========');
    developer.log('Audiences: ' + JsonEncoder().convert(converted['audiences']));
    developer.log('Visit Tallies: ' +
        JsonEncoder().convert(converted['currentVisit']['tallies']));
    developer.log('Badges: ' + JsonEncoder().convert(converted['badges']));
  }

  void _logVisitorId(String visitorId) {
    developer.log('=========Visitor Id Changed =========');
    developer.log('VisitorId: ' + visitorId);
    setState(() {
      currentVisitorId = visitorId;
    });
  }

  void _logRemoteCommand(String name, dynamic payload) {
    developer.log('=========$name Remote Command Response=========');
    developer.log(JsonEncoder().convert(payload));
  }

  void _setRandomConsentCategories() {
    List<ConsentCategories> list = [
      ConsentCategories.affiliates,
      ConsentCategories.analytics,
      ConsentCategories.bigData,
      ConsentCategories.cdp,
      ConsentCategories.cookieMatch,
      ConsentCategories.crm,
      ConsentCategories.displayAds,
      ConsentCategories.email,
      ConsentCategories.engagement,
      ConsentCategories.misc,
      ConsentCategories.mobile,
      ConsentCategories.monitoring,
      ConsentCategories.personalization,
      ConsentCategories.social
    ];
    list = _shuffleCategories(list)!;
    Tealium.setConsentCategories(list.sublist(0, 3));
  }

  List<ConsentCategories>? _shuffleCategories(List<ConsentCategories> items) {
    var random = new Random();
    for (var i = items.length - 1; i > 0; i--) {
      var n = random.nextInt(i + 1);
      var temp = items[i];
      items[i] = items[n];
      items[n] = temp;
      return items;
    }
  }

  _joinTrace() {
    setState(() {
      result = traceIdValue.text;
      Tealium.joinTrace(result);
    });
  }

  _setIdentity() {
    var identity = userIdValue.text;
    Tealium.addToDataLayer({visitorIdentityKey: identity}, Expiry.forever);
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('TealiumFlutterPluginExample'),
        ),
        body: _listView(),
      ),
    );
  }
}

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

1 回复

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


在Flutter项目中集成和使用Tealium进行数据分析与跟踪,可以通过调用Tealium的SDK来实现。虽然Tealium本身并没有直接为Flutter提供官方的插件,但你可以通过一些变通的方法来实现集成,比如使用Platform Channels来与原生代码进行交互。

以下是一个基本的步骤和代码示例,展示了如何在Flutter项目中集成和使用Tealium。

1. 设置原生项目

iOS

  1. 在你的ios/目录下,打开Podfile并添加Tealium SDK的依赖。
platform :ios, '10.0'

target 'Runner' do
  use_frameworks!
  
  # 其他依赖
  pod 'TealiumSDK', '~> X.Y.Z'  # 替换为实际的版本号
  
  # Flutter 依赖
  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end
  1. 运行pod install来安装依赖。

  2. AppDelegate.swift中初始化Tealium SDK。

import UIKit
import Flutter
import TealiumSDK  // 导入Tealium SDK

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    
    // 初始化Tealium SDK
    let config = TealiumConfig(
      account: "your_account",  // 替换为你的Tealium账户
      profile: "your_profile",  // 替换为你的Tealium配置文件
      environment: "your_environment"  // 替换为你的环境(如:production, staging)
    )
    Tealium.shared.initialize(with: config)
    
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

Android

  1. 在你的android/app/build.gradle文件中添加Tealium SDK的依赖。
dependencies {
    implementation 'com.tealium:tealiumsdk:X.Y.Z'  // 替换为实际的版本号
    // 其他依赖
}
  1. MainActivity.kt(或MainActivity.java)中初始化Tealium SDK。
package com.example.yourapp

import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
import com.tealium.open.TealiumConfig
import com.tealium.open.Tealium

class MainActivity: FlutterActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 初始化Tealium SDK
        val config = TealiumConfig.Builder()
            .setAccount("your_account")  // 替换为你的Tealium账户
            .setProfile("your_profile")  // 替换为你的Tealium配置文件
            .setEnvironment("your_environment")  // 替换为你的环境(如:production, staging)
            .build()
        Tealium.initialize(this, config)
    }
}

2. 创建Flutter Platform Channel

在你的Flutter项目中,创建一个新的Dart文件(例如tealium_bridge.dart),用于定义与原生代码交互的接口。

import 'package:flutter/services.dart';

class TealiumBridge {
  static const MethodChannel _channel = MethodChannel('com.example.yourapp/tealium');

  static Future<void> trackEvent(String eventName, Map<String, dynamic> attributes) async {
    try {
      await _channel.invokeMethod('trackEvent', {
        'eventName': eventName,
        'attributes': attributes,
      });
    } on PlatformException catch (e) {
      print("Failed to track event: '${e.message}'.");
    }
  }
}

然后在你的原生代码中实现这个方法。

iOS

AppDelegate.swift或创建一个新的Swift文件(例如TealiumBridge.swift)中实现。

import Flutter
import TealiumSDK

@objc class TealiumBridge: NSObject, FlutterMethodChannelDelegate {
    static let shared = TealiumBridge()
    
    private let channel = FlutterMethodChannel(name: "com.example.yourapp/tealium", binaryMessenger: FlutterEngine.instance()?.binaryMessenger)
    
    override init() {
        super.init()
        channel.setMethodCallHandler(self.handleMethodCall)
    }
    
    func handleMethodCall(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        if call.method == "trackEvent" {
            guard let arguments = call.arguments as? [String: Any],
                  let eventName = arguments["eventName"] as? String,
                  let attributes = arguments["attributes"] as? [String: Any] else {
                result(FlutterError(code: "INVALID_ARGUMENT", message: "Invalid argument passed to trackEvent", details: nil))
                return
            }
            
            // 使用Tealium SDK跟踪事件
            Tealium.shared.trackEvent(eventName, attributes: attributes as [AnyHashable : Any])
            result(nil)
        } else {
            result(FlutterError(code: "UNKNOWN_METHOD", message: "Unknown method called on TealiumBridge", details: nil))
        }
    }
}

确保在AppDelegate.swift中注册这个桥接器。

GeneratedPluginRegistrant.register(with: self)
TealiumBridge.shared.channel.setMethodCallHandler(TealiumBridge.shared)

Android

MainActivity.kt或创建一个新的Kotlin文件(例如TealiumBridge.kt)中实现。

package com.example.yourapp

import android.content.Context
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant
import com.tealium.open.Tealium

class TealiumBridge(private val context: Context) {
    private val channel = MethodChannel(FlutterEngine.getInstance().dartExecutor.binaryMessenger, "com.example.yourapp/tealium")

    init {
        channel.setMethodCallHandler { call, result ->
            if (call.method == "trackEvent") {
                val arguments = call.arguments as? Map<String, Any>
                val eventName = arguments?.get("eventName") as? String
                val attributes = arguments?.get("attributes") as? Map<String, Any>

                eventName?.let { name ->
                    attributes?.let { attrs ->
                        // 使用Tealium SDK跟踪事件
                        Tealium.trackEvent(name, attrs)
                        result.success(null)
                    } ?: result.error("INVALID_ARGUMENT", "Attributes cannot be null", null)
                } ?: result.error("INVALID_ARGUMENT", "Event name cannot be null", null)
            } else {
                result.notImplemented()
            }
        }
    }
}

// 在MainActivity中注册这个桥接器
class MainActivity: FlutterActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        GeneratedPluginRegistrant.registerWith(flutterEngine)
        TealiumBridge(this)
    }
}

3. 在Flutter中使用TealiumBridge

现在你可以在你的Flutter应用中调用TealiumBridge.trackEvent来跟踪事件了。

import 'package:yourapp/tealium_bridge.dart';

void _trackCustomEvent() {
  Map<String, dynamic> attributes = {
    'key1': 'value1',
    'key2': 'value2',
  };
  TealiumBridge.trackEvent('custom_event_name', attributes);
}

请注意,上述代码是一个基本的示例,可能需要根据你的具体需求进行调整。此外,确保你遵循了Tealium SDK的文档和最佳实践来正确配置和使用SDK。

回到顶部