Flutter用户互动与数据分析插件webengage_flutter的使用

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

Flutter用户互动与数据分析插件webengage_flutter的使用

WebEngage Flutter SDK

WebEngage Flutter SDK 是一个用于在Flutter应用程序中集成用户互动和数据分析功能的插件。它允许开发者通过推送通知、InApp消息和其他渠道与用户进行互动,并收集用户行为数据以便进行深入分析。更多信息请参阅官方网站官方文档

更多信息

  • 您可以查看示例main.dart以了解如何在Flutter应用中使用WebEngage。

插件信息

您可以从Pub.dev获取WebEngage Flutter SDK插件。

问题?

如果您有任何疑问或需要进一步的帮助,请联系我们的支持团队

示例代码

以下是一个完整的示例demo,展示了如何在Flutter项目中使用webengage_flutter插件:

import 'dart:io';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:webengage_flutter/webengage_flutter.dart';
import 'package:intl/intl.dart';

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late WebEngagePlugin _webEngagePlugin;
  late String os;

  // 回调函数定义
  void _onPushClick(Map<String, dynamic>? message, String? s) {
    print("Push click callback. Payload " + message.toString());
  }

  void _onPushActionClick(Map<String, dynamic>? message, String? s) {
    print("Push action click callback. Payload " + message.toString());
    print("SelectedId " + s.toString());
  }

  void _onInAppPrepared(Map<String, dynamic>? message) {
    print("Inapp prepared callback. Payload " + message.toString());
  }

  void _onInAppClick(Map<String, dynamic>? message, String? s) {
    print("Inapp click callback. Payload " + message.toString());
  }

  void _onInAppShown(Map<String, dynamic>? message) {
    print("Callback on inapp shown. Payload " + message.toString());
  }

  void _onInAppDismiss(Map<String, dynamic>? message) {
    print("Callback on inapp dismiss. Payload " + message.toString());
  }

  void _onTokenInvalidated(Map<String, dynamic>? message) {
    print("tokenInvalidated callback received " + message.toString());
    WebEngagePlugin.setSecureToken("USER_NAME", "REPLACE_JWT_TOKEN_HERE");
  }

  void _listenToAnonymousID() {
    _webEngagePlugin.anonymousActionStream.listen((event) {
      setState(() {
        data = "${event}";
      });
    });
  }

  Future<void> initPlatformState() async {
    if (Platform.isAndroid) {
      if (await Permission.notification.request().isGranted) {
        print("Notification permission is granted");
        WebEngagePlugin.setUserDevicePushOptIn(true);
      } else {
        print("Notification permission is denied.");
        WebEngagePlugin.setUserDevicePushOptIn(false);
      }
    }
  }

  void initWebEngage() {
    _webEngagePlugin = new WebEngagePlugin();
    _webEngagePlugin.setUpPushCallbacks(_onPushClick, _onPushActionClick);
    _webEngagePlugin.setUpInAppCallbacks(
        _onInAppClick, _onInAppShown, _onInAppDismiss, _onInAppPrepared);
    _webEngagePlugin.tokenInvalidatedCallback(_onTokenInvalidated);
    subscribeToPushCallbacks();
    subscribeToTrackDeeplink();
    subscribeToAnonymousIDCallback();
    _listenToAnonymousID();
  }

  var data = "";
  var anonymousId = "null";

  void _openLoginModal() {
    // 登录对话框逻辑
  }

  void showToast(String msg) {
    // 显示Toast消息
  }

  void subscribeToPushCallbacks() async {
    // Push回调订阅逻辑
  }

  void subscribeToTrackDeeplink() {
    // DeepLink跟踪逻辑
  }

  void subscribeToAnonymousIDCallback() {
    // 匿名ID回调订阅逻辑
  }

  final navigatorKey = GlobalKey<NavigatorState>();

  void showDialogWithMessage(String msg) {
    // 显示对话框逻辑
  }

  @override
  void initState() {
    super.initState();
    initPlatformState();
    initWebEngage();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: navigatorKey,
      home: Scaffold(
        appBar: AppBar(
          title: Text('WebEngage Example'),
        ),
        body: ListView(
          children: <Widget>[
            ListTile(
              title: Text("Login"),
              onTap: () {
                String userName = "REPLACE_YOUR_USERNAME";
                WebEngagePlugin.userLogin(userName);
                showToast("Login-" + userName);
              },
            ),
            ListTile(
              title: Text("Logout"),
              onTap: () {
                WebEngagePlugin.userLogout();
                showToast("Logout");
              },
            ),
            ListTile(
              title: Text("Set FirstName"),
              onTap: () {
                WebEngagePlugin.setUserFirstName('Sourabh');
                showToast("User FirstName- Sourabh");
              },
            ),
            ListTile(
              title: Text("Track Event with no attributes"),
              onTap: () {
                WebEngagePlugin.trackEvent('Added to Cart');
                showToast("Added to Cart tracked ");
              },
            ),
            ListTile(
              title: Text("Opt-In Push, InApp, email, sms, whatsapp, viber"),
              onTap: () {
                WebEngagePlugin.setUserOptIn('in_app', true);
                WebEngagePlugin.setUserOptIn('sms', true);
                WebEngagePlugin.setUserOptIn('push', true);
                WebEngagePlugin.setUserOptIn('email', true);
                WebEngagePlugin.setUserOptIn('whatsapp', true);
                WebEngagePlugin.setUserOptIn('viber', true);
                showToast("Opt-In all channels");
              },
            ),
            ListTile(
              title: Text("Opt-Out Push, InApp, email, sms, whatsapp, viber"),
              onTap: () {
                WebEngagePlugin.setUserOptIn('in_app', false);
                WebEngagePlugin.setUserOptIn('sms', false);
                WebEngagePlugin.setUserOptIn('push', false);
                WebEngagePlugin.setUserOptIn('email', false);
                WebEngagePlugin.setUserOptIn('whatsapp', false);
                WebEngagePlugin.setUserOptIn('viber', false);
                showToast("Opt-Out all channels");
              },
            ),
            ListTile(
              title: Text("Track event with attributes"),
              onTap: () {
                WebEngagePlugin.trackEvent('Order Placed', {'Amount': 808.48});
                showToast("Order Placed tracked Amount: 808.48");
              },
            ),
            ListTile(
              title: Text("Track Screen"),
              onTap: () {
                WebEngagePlugin.trackScreen('Home Page');
                showToast("Track Screen :Home Page");
              },
            ),
            ListTile(
              title: Text("Set User attribute with string value "),
              onTap: () {
                WebEngagePlugin.setUserAttribute("twitterusename", "saurav12994");
                showToast("twitterusename:saurav12994");
              },
            ),
            ListTile(
              title: Text("Start GAID Tracking"),
              onTap: () {
                WebEngagePlugin.startGAIDTracking();
                showToast("Started GAID Tracking");
              },
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _webEngagePlugin.pushSink.close();
    _webEngagePlugin.pushActionSink.close();
    _webEngagePlugin.trackDeeplinkURLStreamSink.close();
    super.dispose();
  }
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

此代码提供了一个基本框架,展示了如何初始化WebEngage插件并设置各种回调函数。此外,还包括了一些常见的操作,如登录、登出、设置用户属性、跟踪事件等。根据您的具体需求,您可以进一步扩展和完善这些功能。


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

1 回复

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


当然,以下是一个关于如何在Flutter项目中使用webengage_flutter插件来实现用户互动与数据分析功能的示例代码。

首先,你需要在你的Flutter项目中添加webengage_flutter依赖。打开你的pubspec.yaml文件,并添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  webengage_flutter: ^最新版本号  # 请替换为当前最新版本号

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

接下来,在你的Flutter应用中进行以下设置和使用:

  1. 初始化WebEngage

在你的应用的入口文件(通常是main.dart)中初始化WebEngage。你需要提供你的WebEngage应用密钥。

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

void main() {
  // 初始化WebEngage
  WebEngage.initialize(
    appKey: 'YOUR_APP_KEY',  // 替换为你的WebEngage应用密钥
  );

  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 StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo Home Page'),
      ),
      body: Center(
        child: Text('Hello, WebEngage!'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 示例:记录一个自定义事件
          WebEngage.trackCustomEvent(eventName: 'custom_event_name', properties: {'key': 'value'});
        },
        tooltip: 'Track Event',
        child: Icon(Icons.add),
      ),
    );
  }
}
  1. 用户属性设置

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

// 设置用户属性
Map<String, dynamic> userProperties = {
  'name': 'John Doe',
  'email': 'john.doe@example.com',
  'age': 30,
};
WebEngage.setUserProperties(userProperties);
  1. 推送通知处理

为了处理从WebEngage发送的推送通知,你需要处理设备接收到的远程通知。这通常在你的应用的AppDelegate(iOS)或MainActivity(Android)中进行设置。

iOS (AppDelegate.swift)

import UIKit
import UserNotifications
import Flutter
import webengage_flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

  override func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    WebEngageFlutterPlugin.sharedInstance().application(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler)
  }
}

Android (MainActivity.kt)

确保你的MainActivity.kt文件正确处理了远程通知。通常,Flutter引擎会处理大部分工作,但你需要确保WebEngage的初始化在适当的位置。

package com.example.yourapp

import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant
import com.webengage.sdk.android.WebEngage

class MainActivity: FlutterActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        GeneratedPluginRegistrant.registerWith(flutterEngine)
        
        // 初始化WebEngage(通常在Application类中完成,但这里作为示例)
        WebEngage.initialize(this, "YOUR_APP_KEY")
    }
}

请注意,实际的推送通知处理可能需要更多的配置,具体取决于你的项目结构和需求。

这个示例展示了如何在Flutter项目中集成和使用webengage_flutter插件进行用户互动和数据分析。根据你的具体需求,你可能需要调整这些代码。务必参考WebEngage的官方文档以获取更多详细信息和最佳实践。

回到顶部