Flutter营销自动化插件optimove_flutter的使用

Flutter营销自动化插件optimove_flutter的使用

在本指南中,我们将讨论如何为您的应用集成Optimove Flutter SDK。

集成指南

设置

以下是集成Optimove Flutter SDK所需执行的步骤:

  1. 初始化SDK
  2. 跟踪客户
  3. 跟踪事件

移动消息传递

以下是设置移动消息传递所需执行的步骤:

  1. 推送设置
  2. 应用内设置
  3. 延迟深度链接
  4. 测试和故障排除

注意: 要解锁这些功能,您需要将相关的OptiMobile渠道添加到您的Optimove包中。如果您在Optimove实例中看不到此功能,请联系您的客户成功经理以了解更多信息。

许可证

OptimoveSDK for Flutter 可用作 MIT 许可证下。


完整示例Demo

以下是一个完整的示例代码,演示了如何在Flutter应用中使用optimove_flutter插件。

import 'dart:async';
import 'dart:convert';

import 'package:Optimove/widgets/location_section.dart';
import 'package:flutter/material.dart';
import 'package:optimove_flutter/optimove_flutter.dart';

import 'inbox.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(home: HomePage());
  }
}

class HomePage extends StatefulWidget {
  [@override](/user/override)
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<HomePage> {
  late final TextEditingController userIdTextController;
  late final TextEditingController emailTextController;

  late final TextEditingController pageTitleTextController;
  late final TextEditingController pageCategoryTextController;

  late final TextEditingController eventNameTextController;

  String optimoveVisitorId = "";
  Map<String, dynamic> eventParams = {};

  [@override](/user/override)
  void initState() {
    super.initState();
    initListeners();
    getIdentifiers();
    userIdTextController = TextEditingController();
    emailTextController = TextEditingController();

    pageTitleTextController = TextEditingController();
    pageCategoryTextController = TextEditingController();

    eventNameTextController = TextEditingController();
  }

  Future<void> initListeners() async {
    Optimove.setPushOpenedAndDeeplinkHandlers((push) {
      _showAlert('打开推送', [
        Text(push.title ?? '无标题'),
        Text(push.message ?? '无消息'),
        const Text(''),
        Text('操作按钮点击: ${push.actionId ?? '无'}'),
        const Text('数据:'),
        Text(jsonEncode(push.data))
      ]);
    }, (outcome) {
      var children = [Text('Url: ${outcome.url}'), Text('解析: ${outcome.resolution}')];

      if (outcome.resolution == OptimoveDeepLinkResolution.LinkMatched) {
        children.addAll([
          Text('链接标题: ${outcome.content?.title}'),
          Text('链接描述: ${outcome.content?.description}'),
          const Text('链接数据:'),
          Text(jsonEncode(outcome.linkData))
        ]);
      }

      _showAlert('Optimove 深度链接', children);
    });

    Optimove.setPushReceivedHandler((push) {
      _showAlert('收到推送', [
        Text(push.title ?? '无标题'),
        Text(push.message ?? '无消息'),
        const Text('数据:'),
        Text(jsonEncode(push.data))
      ]);
    });

    Optimove.setInAppDeeplinkHandler((inAppPress) {
      _showAlert('Optimove 应用内深度链接', [
        Text('消息ID: ${inAppPress.messageId}'),
        Text('消息数据: ${jsonEncode(inAppPress.messageData)}'),
        Text('深度链接数据: ${jsonEncode(inAppPress.deepLinkData)}'),
      ]);
    });
  }

  Future<void> getIdentifiers() async {
    optimoveVisitorId = await Optimove.getVisitorId();
    setState(() {});
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
          colorScheme: const ColorScheme(
        brightness: Brightness.light,
        primary: Color.fromARGB(255, 255, 133, 102),
        onPrimary: Colors.white,
        secondary: Colors.pink,
        onSecondary: Colors.pink,
        error: Colors.pink,
        onError: Colors.pink,
        background: Colors.pink,
        onBackground: Colors.pink,
        surface: Colors.pink,
        onSurface: Colors.black,
      )),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Optimove Flutter QA'),
        ),
        body: Padding(
          padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
          child: SingleChildScrollView(
            child: Column(
              children: [
                _userInfoSection(),
                _getUserIdentitySection(),
                const SizedBox(height: 8),
                _getPushSection(),
                const SizedBox(height: 8),
                _getReportEventSection(),
                const SizedBox(height: 8),
                _getScreenVisitSection(),
                const SizedBox(height: 8),
                _getInAppSection(),
                const SizedBox(height: 8),
                LocationSection(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _userInfoSection() {
    return Card(
      color: const Color.fromARGB(255, 167, 184, 204),
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const SizedBox(height: 8),
            Container(alignment: Alignment.centerLeft, child: Text("当前访客ID: $optimoveVisitorId")),
          ],
        ),
      ),
    );
  }

  Widget _getUserIdentitySection() {
    return Card(
      color: const Color.fromARGB(255, 167, 184, 204),
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            TextField(
                controller: userIdTextController,
                decoration: const InputDecoration(
                  hintText: '用户ID',
                )),
            ElevatedButton(
                style: _getButtonStyle(),
                onPressed: () {
                  Optimove.setUserId(userId: userIdTextController.text);
                  getIdentifiers();
                },
                child: const Text("设置用户ID")),
            TextField(
                controller: emailTextController,
                decoration: const InputDecoration(
                  hintText: '电子邮件',
                )),
            ElevatedButton(
                style: _getButtonStyle(),
                onPressed: () {
                  Optimove.setUserEmail(email: emailTextController.text);
                },
                child: const Text("设置电子邮件")),
            ElevatedButton(
                style: _getButtonStyle(),
                onPressed: () {
                  Optimove.registerUser(userId: userIdTextController.text, email: emailTextController.text);
                  getIdentifiers();
                },
                child: const Text("注册用户")),
            ElevatedButton(
                style: _getButtonStyle(),
                onPressed: () {
                  Optimove.signOutUser();
                  getIdentifiers();
                },
                child: const Text("注销用户")),
          ],
        ),
      ),
    );
  }

  Widget _getScreenVisitSection() {
    return Card(
      color: const Color.fromARGB(255, 167, 184, 204),
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            TextField(
                controller: pageTitleTextController,
                decoration: const InputDecoration(
                  hintText: '页面标题',
                )),
            TextField(
                controller: pageCategoryTextController,
                decoration: const InputDecoration(
                  hintText: '页面分类(可选)',
                )),
            ElevatedButton(
                style: _getButtonStyle(),
                onPressed: () {
                  if (pageCategoryTextController.text.isEmpty) {
                    Optimove.reportScreenVisit(screenName: pageTitleTextController.text);
                  } else {
                    Optimove.reportScreenVisit(screenName: pageTitleTextController.text, screenCategory: pageCategoryTextController.text);
                  }
                },
                child: const Text("报告页面访问")),
          ],
        ),
      ),
    );
  }

  Widget _getInAppSection() {
    return Card(
      color: const Color.fromARGB(255, 167, 184, 204),
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            ElevatedButton(
                style: _getButtonStyle(),
                onPressed: () async {
                  Navigator.push(context, MaterialPageRoute(builder: (context) => Inbox()));
                },
                child: const Text('收件箱')),
            ElevatedButton(
                style: _getButtonStyle(),
                onPressed: () async {
                  var summary = await Optimove.inAppGetInboxSummary();
                  _showAlert('应用内收件箱摘要', [Text('总数: ${summary?.totalCount} 未读: ${summary?.unreadCount}')]);
                },
                child: const Text('应用内收件箱摘要')),
            ElevatedButton(
                style: _getButtonStyle(),
                onPressed: () async {
                  await Optimove.inAppUpdateConsent(true);
                  _showAlert('应用内同意', [const Text('同意应用内消息')]);
                },
                child: const Text('同意')),
            ElevatedButton(
                style: _getButtonStyle(),
                onPressed: () async {
                  await Optimove.inAppUpdateConsent(false);
                  _showAlert('应用内同意', [const Text('拒绝应用内消息')]);
                },
                child: const Text('拒绝')),
          ],
        ),
      ),
    );
  }

  Widget _getPushSection() {
    return Card(
      color: const Color.fromARGB(255, 167, 184, 204),
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            ElevatedButton(
                style: _getButtonStyle(),
                onPressed: () {
                  Optimove.pushRequestDeviceToken();
                },
                child: const Text("注册推送")),
            ElevatedButton(
                style: _getButtonStyle(),
                onPressed: () {
                  Optimove.pushUnregister();
                },
                child: const Text("取消注册推送")),
          ],
        ),
      ),
    );
  }

  Widget _getReportEventSection() {
    return Card(
      color: const Color.fromARGB(255, 167, 184, 204),
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            TextField(
                controller: eventNameTextController,
                decoration: const InputDecoration(
                  hintText: '事件名称',
                )),
            ElevatedButton(
                style: _getButtonStyle(),
                onPressed: () {
                  Optimove.reportEvent(event: eventNameTextController.text, parameters: {"string_param": "some_param"});
                },
                child: const Text("报告事件")),
          ],
        ),
      ),
    );
  }

  void _showAlert(String title, List<Widget> children) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text(title),
            content: SingleChildScrollView(
              child: ListBody(
                children: children,
              ),
            ),
            actions: [
              TextButton(
                child: const Text('确定'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        });
  }

  ButtonStyle _getButtonStyle() {
    return ElevatedButton.styleFrom(shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16))));
  }
}

更多关于Flutter营销自动化插件optimove_flutter的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter营销自动化插件optimove_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


Optimove 是一个用于营销自动化和客户数据平台的解决方案,它允许开发者通过集成 SDK 来跟踪用户行为、发送个性化消息和分析用户数据。optimove_flutter 是一个 Flutter 插件,用于在 Flutter 应用中集成 Optimove 的功能。

以下是使用 optimove_flutter 插件的步骤和基本用法:

1. 添加依赖

首先,在你的 pubspec.yaml 文件中添加 optimove_flutter 依赖:

dependencies:
  optimove_flutter: ^1.0.0  # 请使用最新的版本号

然后运行 flutter pub get 来安装依赖。

2. 初始化 Optimove

在你的 Flutter 应用中初始化 Optimove。通常,你可以在 main.dart 文件中进行初始化:

import 'package:optimove_flutter/optimove_flutter.dart';

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

  // 初始化 Optimove
  await OptimoveFlutter.initialize(
    tenantToken: 'YOUR_TENANT_TOKEN',  // 替换为你的租户令牌
    config: 'YOUR_CONFIG',            // 替换为你的配置
  );

  runApp(MyApp());
}

3. 设置用户身份

在用户登录或注册时,设置用户的身份信息:

OptimoveFlutter.setUserId('USER_ID');  // 替换为用户的唯一标识符

4. 跟踪用户事件

你可以使用 trackEvent 方法来跟踪用户的行为事件:

OptimoveFlutter.trackEvent(
  eventName: 'Event_Name',  // 事件名称
  parameters: {
    'param1': 'value1',     // 事件参数
    'param2': 'value2',
  },
);

5. 发送推送通知

Optimove 支持发送推送通知。你可以使用以下方法来注册设备以接收推送通知:

await OptimoveFlutter.registerPushToken('PUSH_TOKEN');  // 替换为设备的推送令牌

6. 处理推送通知

你可以在应用中处理收到的推送通知:

OptimoveFlutter.onPushReceived((Map<String, dynamic> notification) {
  // 处理推送通知
  print('Received notification: $notification');
});

7. 用户属性

你可以设置用户属性,以便在 Optimove 中进行更精细的用户细分:

OptimoveFlutter.setUserAttributes({
  'attribute1': 'value1',  // 用户属性
  'attribute2': 'value2',
});

8. 退出登录

当用户退出登录时,清除用户身份信息:

OptimoveFlutter.clearUserId();

9. 调试和日志

你可以启用调试模式来查看 Optimove 的日志:

OptimoveFlutter.setDebugMode(true);
回到顶部