Flutter核心功能扩展插件flutter_aepcore的使用

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

Flutter核心功能扩展插件flutter_aepcore的使用

flutter_aepcore 是一个Flutter插件,用于在iOS和Android平台上集成Adobe Experience Platform (AEP) Core SDK。通过Dart代码可以实现与Flutter应用程序的集成。以下是关于如何使用flutter_aepcore的详细说明和完整示例。

目录


安装

  1. pubspec.yaml文件中添加flutter_aepcore依赖:

    dependencies:
      flutter_aepcore: ^最新版本号
    
  2. 运行以下命令来安装插件:

    flutter pub get
    
  3. 对于iOS项目,确保在ios目录下运行pod install以链接库到Xcode项目:

    cd ios
    pod install
    

使用

初始化

初始化SDK应在原生代码中完成(iOS的AppDelegate/SceneDelegate和Android的Application类)。初始化时,确保将SDK包装类型设置为Flutter,然后再启动SDK。

Core
  1. 导入Core

    import 'package:flutter_aepcore/flutter_aepcore.dart';
    
  2. 获取Core版本

    String version = await MobileCore.extensionVersion;
    print('Core SDK Version: $version');
    
  3. 更新SDK配置

    MobileCore.updateConfiguration({"key": "value"});
    
  4. 清除配置更新

    MobileCore.clearUpdatedConfiguration();
    
  5. 控制SDK日志级别

    MobileCore.setLogLevel(LogLevel.error);
    MobileCore.setLogLevel(LogLevel.warning);
    MobileCore.setLogLevel(LogLevel.debug);
    MobileCore.setLogLevel(LogLevel.trace);
    
  6. 获取当前隐私状态

    PrivacyStatus result;
    
    try {
      result = await MobileCore.privacyStatus;
      print('Current Privacy Status: $result');
    } on PlatformException {
      print("Failed to get privacy status");
    }
    
  7. 设置隐私状态

    MobileCore.setPrivacyStatus(PrivacyStatus.opt_in);
    MobileCore.setPrivacyStatus(PrivacyStatus.opt_out);
    MobileCore.setPrivacyStatus(PrivacyStatus.unknown);
    
  8. 获取SDK身份

    String result = "";
    
    try {
      result = await MobileCore.sdkIdentities;
      print('SDK Identities: $result');
    } on PlatformException {
      print("Failed to get sdk identities");
    }
    
  9. 分发Event Hub事件

    final Event event = Event({
      "eventName": "testEventName",
      "eventType": "testEventType",
      "eventSource": "testEventSource",
      "eventData": {"eventDataKey": "eventDataValue"}
    });
    
    try {
      await MobileCore.dispatchEvent(event);
      print("Event dispatched successfully");
    } on PlatformException catch (e) {
      print("Failed to dispatch event: ${e.message}");
    }
    
  10. 分发Event Hub事件并带回调

    Event result;
    final Event event = Event({
      "eventName": "testEventName",
      "eventType": "testEventType",
      "eventSource": "testEventSource",
      "eventData": {"eventDataKey": "eventDataValue"}
    });
    
    try {
      result = await MobileCore.dispatchEventWithResponseCallback(event, 1000);
      print("Event dispatched with response: $result");
    } on PlatformException catch (e) {
      print("Failed to dispatch event: ${e.message}");
    }
    
  11. 重置身份

    MobileCore.resetIdentities();
    
  12. 跟踪应用操作

    重要trackAction通过Edge Bridge和Edge Network扩展支持。

    MobileCore.trackAction("myAction", data: {"key1": "value1"});
    
  13. 跟踪应用状态

    重要trackState通过Edge Bridge和Edge Network扩展支持。

    MobileCore.trackState("myState", data: {"key1": "value1"});
    
Identity
  1. 导入Identity

    import 'package:flutter_aepcore/flutter_aepidentity.dart';
    
  2. 获取Identity版本

    String version = await Identity.extensionVersion;
    print('Identity SDK Version: $version');
    
  3. 同步标识符

    Identity.syncIdentifier("identifierType", "identifier", MobileVisitorAuthenticationState.authenticated);
    
  4. 同步多个标识符

    Identity.syncIdentifiers({
      "idType1": "idValue1",
      "idType2": "idValue2",
      "idType3": "idValue3"
    });
    
  5. 同步带有认证状态的多个标识符

    Identity.syncIdentifiersWithAuthState({
      "idType1": "idValue1",
      "idType2": "idValue2",
      "idType3": "idValue3"
    }, MobileVisitorAuthenticationState.authenticated);
    
  6. 将访客数据附加到URL

    String result = "";
    
    try {
      result = await Identity.appendToUrl("www.myUrl.com");
      print('URL with visitor data: $result');
    } on PlatformException {
      print("Failed to append URL");
    }
    
  7. 设置广告标识符

    MobileCore.setAdvertisingIdentifier("ad-id");
    
  8. 获取访客数据作为URL查询参数字符串

    String result = "";
    
    try {
      result = await Identity.urlVariables;
      print('URL variables: $result');
    } on PlatformException {
      print("Failed to get url variables");
    }
    
  9. 获取标识符

    List<Identifiable> result;
    
    try {
      result = await Identity.identifiers;
      print('Identifiers: $result');
    } on PlatformException {
      print("Failed to get identifiers");
    }
    
  10. 获取Experience Cloud ID

    String result = "";
    
    try {
      result = await Identity.experienceCloudId;
      print('Experience Cloud ID: $result');
    } on PlatformException {
      print("Failed to get experienceCloudId");
    }
    
  11. AEPMobileVisitorId类

    class Identifiable {
      String get idOrigin;
      String get idType;
      String get identifier;
      MobileVisitorAuthenticationState get authenticationState;
    }
    
Lifecycle

注意:必须在原生代码中实现Lifecycle功能。

Signal
  1. 导入Signal

    import 'package:flutter_aepcore/flutter_aepsignal.dart';
    
  2. 获取Signal版本

    String version = await Signal.extensionVersion;
    print('Signal SDK Version: $version');
    

测试

运行测试:

cd plugins/flutter_{plugin_name}/
flutter test

完整示例Demo

以下是一个完整的示例,展示了如何在Flutter应用程序中使用flutter_aepcore插件。

import 'package:flutter/material.dart';
import 'package:flutter_aepcore/flutter_aepcore.dart';
import 'package:flutter_aepidentity/flutter_aepidentity.dart';

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

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

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _coreVersion = '';
  String _identityVersion = '';
  String _privacyStatus = '';
  String _sdkIdentities = '';
  String _urlWithVisitorData = '';

  [@override](/user/override)
  void initState() {
    super.initState();
    _initializeAEP();
  }

  Future<void> _initializeAEP() async {
    // 获取Core版本
    String coreVersion = await MobileCore.extensionVersion;
    setState(() {
      _coreVersion = coreVersion;
    });

    // 获取Identity版本
    String identityVersion = await Identity.extensionVersion;
    setState(() {
      _identityVersion = identityVersion;
    });

    // 设置日志级别
    MobileCore.setLogLevel(LogLevel.debug);

    // 设置隐私状态
    MobileCore.setPrivacyStatus(PrivacyStatus.opt_in);

    // 获取当前隐私状态
    try {
      PrivacyStatus result = await MobileCore.privacyStatus;
      setState(() {
        _privacyStatus = result.toString();
      });
    } on PlatformException {
      print("Failed to get privacy status");
    }

    // 获取SDK身份
    try {
      String result = await MobileCore.sdkIdentities;
      setState(() {
        _sdkIdentities = result;
      });
    } on PlatformException {
      print("Failed to get sdk identities");
    }

    // 将访客数据附加到URL
    try {
      String result = await Identity.appendToUrl("https://example.com");
      setState(() {
        _urlWithVisitorData = result;
      });
    } on PlatformException {
      print("Failed to append URL");
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text('Core SDK Version: $_coreVersion'),
            SizedBox(height: 8),
            Text('Identity SDK Version: $_identityVersion'),
            SizedBox(height: 8),
            Text('Current Privacy Status: $_privacyStatus'),
            SizedBox(height: 8),
            Text('SDK Identities: $_sdkIdentities'),
            SizedBox(height: 8),
            Text('URL with Visitor Data: $_urlWithVisitorData'),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                // 分发Event Hub事件
                final Event event = Event({
                  "eventName": "testEventName",
                  "eventType": "testEventType",
                  "eventSource": "testEventSource",
                  "eventData": {"eventDataKey": "eventDataValue"}
                });

                MobileCore.dispatchEvent(event).then((_) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Event dispatched successfully')),
                  );
                }).catchError((e) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Failed to dispatch event: ${e.message}')),
                  );
                });
              },
              child: Text('Dispatch Event'),
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                // 跟踪应用操作
                MobileCore.trackAction("myAction", data: {"key1": "value1"});
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('Tracked action: myAction')),
                );
              },
              child: Text('Track Action'),
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                // 跟踪应用状态
                MobileCore.trackState("myState", data: {"key1": "value1"});
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('Tracked state: myState')),
                );
              },
              child: Text('Track State'),
            ),
          ],
        ),
      ),
    );
  }
}

更多关于Flutter核心功能扩展插件flutter_aepcore的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter核心功能扩展插件flutter_aepcore的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter开发中,flutter_aepcore 是一个用于扩展核心功能的插件,它通常与Adobe Experience Platform (AEP) 一起使用,以便在Flutter应用中集成和分析数据。以下是如何在Flutter项目中集成和使用 flutter_aepcore 插件的示例代码。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  flutter_aepcore: ^x.y.z  # 请替换为最新版本号

2. 导入插件

在你的 Dart 文件中,导入 flutter_aepcore 插件:

import 'package:flutter_aepcore/flutter_aepcore.dart';

3. 初始化插件

通常,你会在应用启动时初始化这个插件。例如,在 main.dart 文件的 main 函数中:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 flutter_aepcore 插件
  await FlutterAepCore.initialize();

  runApp(MyApp());
}

4. 配置和使用

flutter_aepcore 插件提供了多种配置和使用方法,下面是一个简单的示例,展示了如何设置扩展并处理事件:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 flutter_aepcore 插件
  await FlutterAepCore.initialize();

  // 配置扩展(这里是一个示例,具体配置取决于你的需求)
  FlutterAepCore.configureExtension(
    extensionName: 'com.adobe.module.core',
    friendlyName: 'Core',
    version: '1.0.0',
    configuration: <String, dynamic>{
      'someKey': 'someValue',  // 替换为你的实际配置
    }
  );

  runApp(MyApp());
}

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter AEP Core Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Press the button to log an event',
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                // 记录一个事件
                FlutterAepCore.logEvent(
                  eventName: 'button_pressed',
                  eventType: 'custom',
                  source: 'my_app',
                  data: <String, dynamic>{
                    'additional_info': 'some_value',
                  }
                );
              },
              child: Text('Log Event'),
            ),
          ],
        ),
      ),
    );
  }
}

注意事项

  1. 版本兼容性:确保你使用的 flutter_aepcore 插件版本与你的 Flutter SDK 版本兼容。
  2. Adobe AEP 账号:使用 Adobe Experience Platform 功能时,你可能需要有一个有效的 Adobe AEP 账号和相应的配置。
  3. 权限:在 Android 和 iOS 上,确保你有适当的权限来收集和发送数据。

以上示例代码展示了如何在 Flutter 应用中集成和使用 flutter_aepcore 插件。根据你的具体需求,你可能需要调整配置和事件记录的逻辑。

回到顶部