Flutter用户管理插件flutter_user_sdk的使用

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

Flutter用户管理插件flutter_user_sdk的使用

User.com Flutter SDK (flutter_user_sdk)

User.com package 帮助开发者跟踪应用程序内的用户活动。支持Flutter 2 & Flutter 3版本。

功能特性

  • 发送自定义事件
  • 发送产品事件
  • 发送屏幕事件
  • 发送通知事件
  • 注册和保存用户数据
  • 接收FCM通知(应用内通知和移动通知)
  • 无网络连接时缓存未发送的请求
  • 网络恢复后重新发送请求

警告:我们正在从通过flutter_local_notifications显示通知迁移到原生Firebase Messaging。当前平台不支持此功能,集成此包需要额外的步骤,详情请参阅项目集成部分。我们希望尽快完成迁移,并使flutter_user_sdk更易于集成。

安装

在您的项目中添加最新版本的包:

flutter pub add flutter_user_sdk

入门指南

要开始使用flutter_user_sdk包,请遵循以下步骤:

  1. 访问User.com并创建或登录到您的应用。
  2. 获取初始化SDK所需的变量 - mobileSdkKeyappDomain
    • App domain是应用程序运行的URL。
    • 要获取mobileSdkKey,请前往设置 -> 应用设置 -> 高级 -> Mobile SDK keys。
  3. SDK 使用 FCM,因此需要 Firebase 项目以确保包正常运行。
    • 在 Firebase 创建 Android 和 iOS 项目。
    • 下载google-services.jsonGoogleServices-Info.plist文件并将其添加到项目中。
    • 在 App Store Connect 中创建.p8 APN 密钥并粘贴到 Firebase 项目中。
    • 在 Firebase 项目中找到服务器密钥:设置 -> Cloud Messaging。
    • 将服务器密钥粘贴到 User.com 应用:设置 -> 应用设置 -> 高级 -> Mobile FCM keys。

项目集成

iOS

不需要额外配置。

Android

/android/build.gradle中添加以下内容:

buildscript {
    ext.kotlin_version = '1.8.10'
    repositories {
        google()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:7.4.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.3'
    }
}

/android/app/build.gradle中设置:

android {
    compileSdkVersion 33
    ...
}

使用示例

下面是一个完整的示例代码,展示了如何使用flutter_user_sdk提供的方法:

import 'dart:math';

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // Initialize SDK and pass arguments.
  // Find your keys on https://user.com/en/
  await UserComSDK.instance.initialize(
    mobileSdkKey: 'paste_your_key_from_user_com',
    appDomain: 'https://testapp.user.com/',
  );

  runApp(const UserComApp());
}

class UserComApp extends StatelessWidget {
  const UserComApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorObservers: [
        // Send screen events when entering new page
        // If using custom routing, make your own observer and
        // use UserSDK.instance.sendScreenEvent()
        // Don't forget to name Routes in settings
        UserSdkNavigatorObserver(),
      ],
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  void _sendCustomEvent() {
    // Send event with data that can be converted to simple types
    UserComSDK.instance.sendCustomEvent(
      eventName: 'user_interacted',
      data: <String, dynamic>{
        'button_id': Random.secure().nextInt(999),
      },
    );
  }

  void _sendCustomEventWithLargePayload() {
    // Send event with nested json
    UserComSDK.instance.sendCustomEvent(
      eventName: 'user_interacted',
      data: testNestedPayloadData,
    );
  }

  void _sendProductEvent() {
    // Define your own product parameters and send product event
    UserComSDK.instance.sendProductEvent(
      event: ProductEvent(
        productId: Random().nextInt(9999).toString(),
        eventType: ProductEventType.addToCart,
        parameters: <String, dynamic>{
          'price': Random().nextDouble(),
          'ref_number': '222',
          'time_spent_in_mins': Random().nextInt(999),
          'converted': true,
          'variant_id': 'qaz123'
        },
      ),
    );
  }

  void _registerUser() {
    // Send more information about the user. You can add custom attributes.
    // Attributes must be simple type.
    UserComSDK.instance.registerUser(
      customer: Customer(
        userId: 'my_own_id_2',
        email: 'my_own_user@gmail.com',
        firstName: 'Test',
        lastName: 'User',
      )
        ..addCustomAttribute('country', 'USA')
        ..addCustomAttribute('has_benefits', true)
        ..addCustomAttribute('sex', 'female')
        ..addCustomAttribute('age', 22),
    );
  }

  @override
  Widget build(BuildContext context) {
    UserComSDK.instance.buildNotificationOnMessageReceived(context: context);

    return Scaffold(
      appBar: AppBar(title: const Text('User SDK Example App')),
      body: Container(
        alignment: Alignment.center,
        padding: const EdgeInsets.all(40.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            ElevatedButton(
              onPressed: () {
                // Pushing new page triggers screen_event
                // Observer must be attached and routes must be named
                Navigator.of(context).push(
                  MaterialPageRoute(
                    settings: const RouteSettings(name: 'ProductPage'),
                    builder: (_) => Scaffold(
                      body: Container(
                        alignment: Alignment.center,
                        child: const Text('ProductPage'),
                      ),
                    ),
                  ),
                );
              },
              child: const Text('Go to Product Page'),
            ),
            ElevatedButton(
              onPressed: () => _sendCustomEvent(),
              child: const Text('Send custom event'),
            ),
            ElevatedButton(
              onPressed: () => _sendCustomEventWithLargePayload(),
              child: const Text('Send large payload event'),
            ),
            ElevatedButton(
              onPressed: () => _sendProductEvent(),
              child: const Text('Send product event'),
            ),
            ElevatedButton(
              onPressed: () => _registerUser(),
              child: const Text('Register user'),
            ),
            ElevatedButton(
              onPressed: () => UserComSDK.instance.logoutUser(),
              child: const Text('Logout user'),
            ),
          ],
        ),
      ),
    );
  }
}

// Simplified service for handling User.com messages that are pushed via FirebaseMessaging.
// Remember to fetch FCM token and pass it to [UserSDK.instance.initialize()].
class FirebaseSimpleService {
  FirebaseSimpleService._();

  factory FirebaseSimpleService() {
    return _instance;
  }

  static final FirebaseSimpleService _instance = FirebaseSimpleService._();

  // Init all Firebase methods
  void initialize(BuildContext context) {
    onInitialMessage();
    onMessageOpenedApp();
    onMessage(context);
    FirebaseMessaging.onBackgroundMessage(_onBackgroundMessage);
  }

  void onInitialMessage() async {
    final remoteMessage = await FirebaseMessaging.instance.getInitialMessage();
    if (remoteMessage == null) return;

    if (UserComSDK.instance.isUserComMessage(remoteMessage.data)) {
      final message = UserComSDK.instance.getPushMessage(remoteMessage.data);

      if (message != null) {
        UserComSDK.instance.notificationClickedEvent(
          id: message.id,
          type: message.type,
        );

        // process with User.com Push Message
      }
    }

    // process other Firebase Messages
  }

  void onMessageOpenedApp() {
    FirebaseMessaging.onMessageOpenedApp.listen(
      (event) {
        if (UserComSDK.instance.isUserComMessage(event.data)) {
          final message = UserComSDK.instance.getPushMessage(event.data);

          if (message != null) {
            UserComSDK.instance.notificationClickedEvent(
              id: message.id,
              type: message.type,
            );
            // process with User.com Push Message
          }
        }
      },

      // process other Firebase Messages
    );
  }

  void onMessage(BuildContext context) {
    FirebaseMessaging.onMessage.listen(
      (event) {
        if (UserComSDK.instance.isUserComMessage(event.data)) {
          // Displaying messages in [buildNotificationOnMessageReceived]
          // can be customized using [onInAppMessage] and [onNotificationMessage]
          UserComSDK.instance.buildNotificationOnMessageReceived(
            context: context,
            message: event,
            onTap: (type, link) {
              if (type == NotificationType.push) {
                // Define here what to do on notification tap
                // For example launchUrl and dismiss notification
              }
              if (type == NotificationType.inApp) {
                // Define here what to do when user tap button that has link
              }
            },
          );
        }

        // ... Process on other messages coming from FCM
      },
    );
  }

  static Future<void> _onBackgroundMessage(RemoteMessage message) async {}
}

以上代码提供了一个完整的示例,演示了如何初始化flutter_user_sdk、发送自定义事件、发送产品事件、注册用户以及处理推送通知等操作。您可以根据实际需求修改和扩展这些代码。


更多关于Flutter用户管理插件flutter_user_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter用户管理插件flutter_user_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何使用Flutter用户管理插件flutter_user_sdk的示例代码案例。请注意,实际使用中你可能需要根据具体的插件版本和API文档进行调整。

首先,确保你已经在pubspec.yaml文件中添加了flutter_user_sdk依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_user_sdk: ^x.y.z  # 请替换为实际的版本号

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

接下来,我们编写一个简单的Flutter应用,展示如何使用flutter_user_sdk进行用户管理。

main.dart

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

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

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

class _MyAppState extends State<MyApp> {
  UserSDK _userSDK = UserSDK.instance;
  User? _currentUser;

  @override
  void initState() {
    super.initState();
    _initializeUserSDK();
  }

  Future<void> _initializeUserSDK() async {
    // 假设这里需要配置一些初始化参数,具体根据文档来
    await _userSDK.initialize();

    // 监听用户状态变化
    _userSDK.userStream.listen((User? user) {
      setState(() {
        _currentUser = user;
      });
    });

    // 尝试获取当前用户
    _currentUser = await _userSDK.getCurrentUser();
  }

  Future<void> _signUp() async {
    try {
      UserCredential credential = await _userSDK.signUp(
        email: 'user@example.com',
        password: 'password123',
        // 其他可能的注册参数,如用户名、昵称等
      );
      print('Sign-Up successful: ${credential.user}');
    } catch (e) {
      print('Sign-Up failed: $e');
    }
  }

  Future<void> _signIn() async {
    try {
      UserCredential credential = await _userSDK.signIn(
        email: 'user@example.com',
        password: 'password123',
      );
      print('Sign-In successful: ${credential.user}');
    } catch (e) {
      print('Sign-In failed: $e');
    }
  }

  Future<void> _signOut() async {
    try {
      await _userSDK.signOut();
      print('Sign-Out successful');
      setState(() {
        _currentUser = null;
      });
    } catch (e) {
      print('Sign-Out failed: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter User SDK Demo'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              if (_currentUser != null)
                Text('Current User: ${_currentUser!.email}'),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: _signUp,
                child: Text('Sign Up'),
              ),
              SizedBox(height: 10),
              ElevatedButton(
                onPressed: _signIn,
                child: Text('Sign In'),
              ),
              SizedBox(height: 10),
              ElevatedButton(
                onPressed: _signOut,
                child: Text('Sign Out'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

说明

  1. 初始化UserSDK:在initState方法中初始化UserSDK并监听用户状态变化。
  2. 注册用户_signUp方法用于注册新用户。
  3. 登录用户_signIn方法用于用户登录。
  4. 登出用户_signOut方法用于用户登出。
  5. 显示当前用户:如果当前有登录用户,显示其邮箱地址。

请注意,这只是一个基本示例,flutter_user_sdk的实际API可能有所不同,你需要参考其官方文档进行相应调整。此外,实际应用中应该处理更多的边界情况和错误处理。

回到顶部