Flutter Web集成Braze插件braze_plugin_web的使用

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

Flutter Web集成Braze插件braze_plugin_web的使用

braze_plugin_web 是一个非官方的用于Flutter Web的Braze插件。它通过JavaScript Interop包装了官方的Braze Web SDK,适用于Web平台。

配置

添加Braze Web SDK脚本

index.html 文件(位于项目的 web 文件夹中)添加以下脚本:

<script type="text/javascript">
  +function(a,p,P,b,y){a.braze={};a.brazeQueue=[];for(var s="BrazeSdkMetadata DeviceProperties Card Card.prototype.dismissCard Card.prototype.removeAllSubscriptions Card.prototype.removeSubscription Card.prototype.subscribeToClickedEvent Card.prototype.subscribeToDismissedEvent Card.fromContentCardsJson Banner CaptionedImage ClassicCard ControlCard ContentCards ContentCards.prototype.getUnviewedCardCount Feed Feed.prototype.getUnreadCardCount ControlMessage InAppMessage InAppMessage.SlideFrom InAppMessage.ClickAction InAppMessage.DismissType InAppMessage.OpenTarget InAppMessage.ImageStyle InAppMessage.Orientation InAppMessage.TextAlignment InAppMessage.CropType InAppMessage.prototype.closeMessage InAppMessage.prototype.removeAllSubscriptions InAppMessage.prototype.removeSubscription InAppMessage.prototype.subscribeToClickedEvent InAppMessage.prototype.subscribeToDismissedEvent InAppMessage.fromJson FullScreenMessage ModalMessage HtmlMessage SlideUpMessage User User.Genders User.NotificationSubscriptionTypes User.prototype.addAlias User.prototype.addToCustomAttributeArray User.prototype.addToSubscriptionGroup User.prototype.getUserId User.prototype.incrementCustomUserAttribute User.prototype.removeFromCustomAttributeArray User.prototype.removeFromSubscriptionGroup User.prototype.setCountry User.prototype.setCustomLocationAttribute User.prototype.setCustomUserAttribute User.prototype.setDateOfBirth User.prototype.setEmail User.prototype.setEmailNotificationSubscriptionType User.prototype.setFirstName User.prototype.setGender User.prototype.setHomeCity User.prototype.setLanguage User.prototype.setLastKnownLocation User.prototype.setLastName User.prototype.setPhoneNumber User.prototype.setPushNotificationSubscriptionType InAppMessageButton InAppMessageButton.prototype.removeAllSubscriptions InAppMessageButton.prototype.removeSubscription InAppMessageButton.prototype.subscribeToClickedEvent FeatureFlag FeatureFlag.prototype.getStringProperty FeatureFlag.prototype.getNumberProperty FeatureFlag.prototype.getBooleanProperty automaticallyShowInAppMessages destroyFeed hideContentCards showContentCards showFeed showInAppMessage toggleContentCards toggleFeed changeUser destroy getDeviceId initialize isPushBlocked isPushPermissionGranted isPushSupported logCardClick logCardDismissal logCardImpressions logContentCardImpressions logContentCardClick logContentCardsDisplayed logCustomEvent logFeedDisplayed logInAppMessageButtonClick logInAppMessageClick logInAppMessageHtmlClick logInAppMessageImpression logPurchase openSession requestPushPermission removeAllSubscriptions removeSubscription requestContentCardsRefresh requestFeedRefresh refreshFeatureFlags requestImmediateDataFlush enableSDK isDisabled setLogger setSdkAuthenticationSignature addSdkMetadata disableSDK subscribeToContentCardsUpdates subscribeToFeedUpdates subscribeToInAppMessage subscribeToSdkAuthenticationFailures toggleLogging unregisterPush wipeData handleBrazeAction subscribeToFeatureFlagsUpdates getAllFeatureFlags".split(" "),i=0;i<s.length;i++){for(var m=s[i],k=a.braze,l=m.split("."),j=0;j<l.length-1;j++)k=k[l[j]];k[l[j]]=(new Function("return function "+m.replace(/\./g,"_")+"(){window.brazeQueue.push(arguments); return true}"))()}window.braze.getCachedContentCards=function(){return new window.braze.ContentCards};window.braze.getCachedFeed=function(){return new window.braze.Feed};window.braze.getUser=function(){return new window.braze.User};window.braze.getFeatureFlag=function(){return new window.braze.FeatureFlag};(y=p.createElement(P)).type='text/javascript';
    y.src='https://js.appboycdn.com/web-sdk/4.7/braze.min.js';
    y.async=1;(b=p.getElementsByTagName(P)[0]).parentNode.insertBefore(y,b)
  }(window,document,'script');
</script>

请确保使用最新的Braze Web SDK加载片段:loading-snippet.js

使用

初始化和基本操作

以下是一个简单的示例,展示如何初始化Braze客户端并执行一些基本操作:

import 'package:braze_plugin_web/braze_plugin_web.dart';

void main() {
  // 初始化Braze客户端
  BrazeClient.initialize(
    apiKey: 'your_api_key', 
    baseUrl: 'your_base_url',
    automaticallyShowInAppMessages: true,
    enableLogging: true,
  );

  // 标识用户
  BrazeClient.identify('test-user');

  // 设置自定义属性
  BrazeClient.setCustomAttribute('test_web_plugin', true);

  // 设置多个自定义属性
  BrazeClient.setCustomAttributes({
    'test_web_plugin_1': 'Hi!',
    'test_web_plugin_2': 27,
  });

  // 记录自定义事件
  BrazeClient.logCustomEvent('test_web_plugin_event', jsonEncode({'prop1': false}));
}

完整示例Demo

下面是一个完整的Flutter Web应用示例,展示了如何使用Braze插件:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:braze_plugin_web/braze_plugin_web.dart';

/// Set the Braze API Key and Base URL with Dart Environment Variables
/// Run Args: --dart-define=apiKey=1234567890 --dart-define=baseUrl=sdk.iad-02.braze.com
void main() => runApp(MyApp());

const String _brazeApiKey = String.fromEnvironment('apiKey');
const String _brazeBaseUrl = String.fromEnvironment('baseUrl');

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Braze Plugin for Web',
      home: BrazeWebExamplePage(),
    );
  }
}

class BrazeWebExamplePage extends StatefulWidget {
  @override
  BrazeWebExamplePageState createState() => BrazeWebExamplePageState();
}

class BrazeWebExamplePageState extends State<BrazeWebExamplePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Braze Web Example'),
      ),
      body: Column(
        children: [
          TextButton(
            child: const Text('Initialize'),
            onPressed: () async {
              BrazeClient.initialize(
                apiKey: _brazeApiKey,
                baseUrl: _brazeBaseUrl,
                automaticallyShowInAppMessages: true,
                enableLogging: true,
              );
            },
          ),
          TextButton(
            child: const Text('Identify'),
            onPressed: () async {
              BrazeClient.identify('test-user');
            },
          ),
          TextButton(
            child: const Text('Set Custom Attribute'),
            onPressed: () async {
              BrazeClient.setCustomAttribute('test_web_plugin', true);
            },
          ),
          TextButton(
            child: const Text('Set Custom Attributes'),
            onPressed: () async {
              BrazeClient.setCustomAttributes({
                'test_web_plugin_1': 'Hi!',
                'test_web_plugin_2': 27,
              });
            },
          ),
          TextButton(
            child: const Text('Log Custom Event'),
            onPressed: () async {
              BrazeClient.logCustomEvent(
                'test_web_plugin_event',
                jsonEncode({'prop1': false}),
              );
            },
          ),
        ],
      ),
    );
  }
}

运行命令

在运行应用时,请通过命令行参数传递API密钥和Base URL:

flutter run --dart-define=apiKey=YOUR_API_KEY --dart-define=baseUrl=YOUR_BASE_URL

替换 YOUR_API_KEYYOUR_BASE_URL 为你的实际Braze API密钥和基础URL。

以上就是关于Flutter Web集成Braze插件braze_plugin_web的基本使用方法和示例代码。希望对你有所帮助!


更多关于Flutter Web集成Braze插件braze_plugin_web的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter Web集成Braze插件braze_plugin_web的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter Web项目中集成并使用braze_plugin_web插件的示例代码案例。这个案例将展示如何初始化Braze插件,并发送一个简单的推送通知。

步骤 1: 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  braze_plugin_web: ^最新版本号  # 请替换为实际的最新版本号

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

步骤 2: 配置Braze

web/index.html文件中添加Braze的配置脚本。你需要从Braze控制台获取你的appIdapiKey

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flutter Web Braze Example</title>
    <!-- Braze Configuration -->
    <script type="text/javascript">
        !function(){var e=document.createElement("script");e.type="text/javascript",e.async=!0,e.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.braze.com/js/app/your-app-id.js";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t)}();

        window.Braze = window.Braze || {};
        window.Braze.init = function(appId, apiKey) {
            Braze.start({
                appId: appId,
                apiKey: apiKey,
                // 其他配置选项...
            });
        };

        // 初始化Braze(使用你的实际appId和apiKey)
        window.Braze.init('your-app-id', 'your-api-key');
    </script>
</head>
<body>
    <script src="main.dart.js" type="application/javascript"></script>
</body>
</html>

步骤 3: 使用Braze插件

在你的Flutter Web项目中,你可以通过braze_plugin_web插件与Braze进行交互。下面是一个简单的示例,展示如何在Flutter中初始化Braze并发送一个简单的日志事件。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Braze Flutter Web Example'),
        ),
        body: Center(
          child: BrazeExample(),
        ),
      ),
    );
  }
}

class BrazeExample extends StatefulWidget {
  @override
  _BrazeExampleState createState() => _BrazeExampleState();
}

class _BrazeExampleState extends State<BrazeExample> {
  @override
  void initState() {
    super.initState();
    // 初始化Braze插件(通常在Flutter侧不需要重复初始化,因为已经在web/index.html中初始化了)
    // 但你可以通过插件调用一些Braze的功能
    BrazePluginWeb.instance.initialize().then((_) {
      // 发送一个简单的日志事件
      BrazePluginWeb.instance.logEvent(
        eventName: 'flutter_event',
        attributes: {'key': 'value'},
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text('Braze has been initialized and an event has been logged.'),
        ElevatedButton(
          onPressed: () {
            // 示例:发送另一个事件
            BrazePluginWeb.instance.logEvent(
              eventName: 'another_flutter_event',
              attributes: {'another_key': 'another_value'},
            );
          },
          child: Text('Log Another Event'),
        ),
      ],
    );
  }
}

注意事项

  1. Braze初始化:在web/index.html中初始化Braze通常就足够了。在Flutter侧调用BrazePluginWeb.instance.initialize()主要是为了与插件接口保持一致,实际上可能不需要再次初始化。
  2. 事件日志:你可以通过logEvent方法发送自定义事件到Braze,这对于用户行为跟踪非常有用。
  3. 配置选项:根据你的需求,你可能需要在Braze的初始化配置中添加更多的选项,如渠道标识、用户属性等。

这个示例展示了如何在Flutter Web项目中集成和使用braze_plugin_web插件。根据你的实际需求,你可能需要调整配置和代码。

回到顶部