Flutter数据传输与发送插件suprsend_flutter_sdk的使用

Flutter数据传输与发送插件suprsend_flutter_sdk的使用

Suprsend 是一个作为服务的通知堆栈平台,可以轻松创建、管理和向终端用户发送通知。SuprSend 提供了一整套功能,使您可以以可靠且可扩展的方式发送通知,并且可以照顾终端用户体验,从而消除了构建任何通知服务的需求。

使用 SuprSend 的好处包括:

  • 您无需在代码中进行供应商集成。您可以轻松地从您的 SuprSend 账户添加/删除/优先化供应商和渠道。
  • 您可以设计所有通道的强大模板,并从一个地方管理它们。
  • 您可以利用强大的功能快速实验通知,同时无需编写单行代码即可照顾终端用户体验。

SDK 使用

此客户端侧 Flutter SDK 可用于发送和跟踪 Android 推送通知、跟踪用户属性和事件。通过此 SDK,您将能够直接从应用触发工作流,并在 Android 设备上呈现推送通知。有关更多详细信息,请参阅 Suprsend 文档。

版本支持

确保您的 minSDK 至少为 API 19 或以上。

安装

步骤 1. 打开您的 Flutter 项目的 pubspec.yaml 文件

在 pubspec.yaml 文件的 dependencies 中添加以下代码:

dependencies:
  flutter:
    sdk: flutter
  suprsend_flutter_sdk: "^2.2.0"

步骤 2. 在终端中运行 flutter pub get,或者在 IntelliJ 或 Android Studio 中点击“Pub get”按钮。

$ flutter pub get

初始化

步骤 1: 在您的 Android 应用中集成 SuprSend

您需要在 MainApplication 类中初始化 SuprSend Flutter SDK。请注意,如果主应用未创建,则需要创建该类。

进入您的 Flutter 项目中的 android 文件夹并执行以下步骤:

import app.suprsend.SSApi; // 导入 SDK

class MainApplication : Application() {

  override fun onCreate() {
    
    // 重要!如果没有这一步,SDK 将无法工作
    SSApi.init(this, workspace_key, workspace_secret)

    // 可选。如果您想支持小米通知框架,请添加以下代码
    SSApi.initXiaomi(this, xiaomi_app_id, xiaomi_api_key)

    // 两个初始化都必须在调用 super() 之前完成
    super.onCreate()
  }
}

为了初始化 SDK,您需要 workspace_key 和 workspace_secret。您可以在 SuprSend 客户端仪表板 中获取这两个令牌。有关更多详细信息,请参阅 文档中的“Workspaces”部分。

步骤 2: 要调用 SuprSend 事件,您需要在 Dart 文件中导入 SuprSend SDK

返回到 Flutter 文件夹并执行以下步骤:

import 'package:suprsend_flutter_sdk/suprsend.dart';

示例代码

以下是完整的示例代码:

import 'dart:async';
import 'dart:collection';
import 'dart:developer';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

import 'package:suprsend_flutter_sdk/suprsend.dart';
import 'package:suprsend_flutter_sdk/log_levels.dart';
import 'package:uni_links/uni_links.dart';

import 'package:suprsend_flutter_inbox/main.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:suprsend_flutter_inbox/store.dart';

void main() {
  runApp(const MaterialApp(home: MyApp()));
}

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  String _userId = "";
  String? _subsId;

  var _propertyKey = "";
  var _propertyValue = "";
  var _propertyDistinctId = "";
  var _propertyMobileNumber = "";
  var _propertyEmail = "";

  final propKeyController = TextEditingController();
  final propValueController = TextEditingController();
  final propDistinctIdController = TextEditingController();
  final propMobileNumberController = TextEditingController();
  final propEmailController = TextEditingController();

  final _userLoginFormKey = GlobalKey<FormState>();
  final _userPropertySetUnsetFormKey = GlobalKey<FormState>();
  final _userMobileFormKey = GlobalKey<FormState>();
  final _userEmailFormKey = GlobalKey<FormState>();

  late final StreamSubscription _linkSub;

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

    propKeyController.addListener(() {
      _propertyKey = propKeyController.text.toString();
    });

    propValueController.addListener(() {
      _propertyValue = propValueController.text.toString();
    });

    propDistinctIdController.addListener(() {
      _propertyDistinctId = propDistinctIdController.text.toString();
    });

    propMobileNumberController.addListener(() {
      _propertyMobileNumber = propMobileNumberController.text.toString();
    });

    propEmailController.addListener(() {
      _propertyEmail = propEmailController.text.toString();
    });
  }

  // 平台消息是异步的,因此我们初始化在一个异步方法中。
  Future<void> initPlatformState() async {
    String platformVersion;
    // 平台消息可能失败,所以我们使用 try/catch PlatformException。
    // 我们还处理了消息可能返回 null 的情况。
    try {
      platformVersion = 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    await initUniLinks();

    suprsend.setLogLevel(LogLevels.VERBOSE);

    var hashMap = HashMap<String, Object>();
    hashMap["flutter_runtime_version"] = Platform.version.replaceAll("\"", "'");
    suprsend.setSuperProperties(hashMap);

    var countsMap = HashMap<String, int>();
    countsMap["app_open_count"] = 1;

    suprsend.user.increment(countsMap);

    // 如果在异步平台消息飞行时小部件从树中移除,我们将丢弃回复而不是调用
    // setState 来更新我们的不存在的外观。
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  Future<void> initUniLinks() async {
    // ... 检查 initialLink
    try {
      final initialLink = await getInitialLink();
      // 解析链接并在不正确的情况下警告用户,但请记住它可能是 `null`。
      if (initialLink != null) {
        print("Initial Link received: $initialLink");
      }
    } on PlatformException catch (exception) {
      // 处理异常并通过警告用户其操作未成功来处理。
      print("Initial Link error occurred: $exception");
    }

    // 将监听器附加到流
    _linkSub = linkStream.listen((String? link) {
      // 解析链接并在不正确的情况下警告用户。
      if (link != null) {
        print("Link stream event received: $link");
      }
    }, onError: (err) {
      // 处理异常并通过警告用户其操作未成功来处理。
      print("Link stream event error occurred: $err");
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return SuprSendProvider(
        workspaceKey: "your workspace key",
        workspaceSecret: "your workspace secret",
        distinctId: "distinct id",
        subscriberId: "subscriber id",
        child: MaterialApp(
            home: Scaffold(
          appBar: AppBar(
            title: Text('Suprsend Client App: $_platformVersion'),
          ),
          body: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: Form(
              key: _userPropertySetUnsetFormKey,
              child: Column(
                mainAxisSize: MainAxisSize.max,
                children: [
                  Row(children: const [
                    Expanded(
                        flex: 10,
                        child: Center(
                          heightFactor: 1.5,
                          child: Text(
                            "",
                            textAlign: TextAlign.center,
                          ),
                        )),
                  ]),
                  Row(children: const [
                    Expanded(
                        flex: 10,
                        child: Center(
                          heightFactor: 2.5,
                          child: Text(
                            "Testing SS Flutter Plugin",
                            textAlign: TextAlign.center,
                            textScaleFactor: 1.6,
                          ),
                        )),
                  ]),
                  Row(children: [
                    Expanded(
                        flex: 10,
                        child: Center(
                          heightFactor: 2.5,
                          child: Text(
                            "Distinct ID: $_userId",
                            textAlign: TextAlign.center,
                            textScaleFactor: 1,
                          ),
                        )),
                  ]),
                  Row(children: const [
                    Expanded(
                        flex: 10,
                        child: Padding(
                            padding: EdgeInsets.fromLTRB(14, 6, 12, 0),
                            child: Text(
                              "User Login form",
                              textAlign: TextAlign.start,
                              textScaleFactor: 1.2,
                            ))),
                  ]),
                  Form(
                      key: _userLoginFormKey,
                      child: Column(mainAxisSize: MainAxisSize.max, children: [
                        Row(children: [
                          Expanded(
                            flex: 10,
                            child: Padding(
                              padding: const EdgeInsets.fromLTRB(12, 12, 6, 6),
                              child: TextFormField(
                                controller: propDistinctIdController,
                                validator: (value) {
                                  if (value == null || value.isEmpty) {
                                    return 'Please enter Distinct ID';
                                  }
                                  return null;
                                },
                                decoration: const InputDecoration(
                                  border: OutlineInputBorder(),
                                  hintText: 'Distinct ID',
                                ),
                              ),
                            ),
                          ),
                        ]),
                        Padding(
                          padding: const EdgeInsets.fromLTRB(6, 6, 6, 60),
                          child: Row(
                            children: [
                              Expanded(
                                  flex: 10,
                                  child: Padding(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 6, vertical: 0),
                                    child: OutlinedButton(
                                      child: const Padding(
                                        padding: EdgeInsets.symmetric(
                                            vertical: 18, horizontal: 12),
                                        child: Text(
                                          "Login with Distinct ID",
                                          textAlign: TextAlign.center,
                                          textScaleFactor: 1.2,
                                        ),
                                      ),
                                      onPressed: () async {
                                        log("Clicked login button");
                                        var validationResult = _userLoginFormKey
                                            .currentState!
                                            .validate();
                                        log("_propertyDistinctId == $_propertyDistinctId");
                                        log("propDistinctIdController.text.toString() == ${propDistinctIdController.text.toString()}");
                                        if (validationResult) {
                                          if (_propertyDistinctId.isNotEmpty) {
                                            setState(() {
                                              log("Before _userId == $_userId");
                                              _userId = _propertyDistinctId;
                                              log("After _userId == $_userId");
                                            });
                                            var hashMap =
                                                HashMap<String, Object>();
                                            hashMap["User_ID"] = _userId;

                                            var countsMap =
                                                HashMap<String, int>();
                                            countsMap["Login_count"] = 1;
                                            suprsend.user.increment(countsMap);

                                            suprsend
                                                .setSuperProperties(hashMap);
                                            suprsend
                                                .identify(_propertyDistinctId);
                                          } else {
                                            print(
                                                "Property Distinct ID must not be empty when calling login()!");
                                          }
                                        } else {
                                          print(
                                              "There are validation errors with your Property Key!");
                                        }
                                      },
                                    ),
                                  )),
                            ],
                          ),
                        )
                      ])),
                  Row(children: const [
                    Expanded(
                        flex: 10,
                        child: Padding(
                            padding: EdgeInsets.fromLTRB(14, 6, 12, 0),
                            child: Text(
                              "User Property Set/Unset form",
                              textAlign: TextAlign.start,
                              textScaleFactor: 1.2,
                            ))),
                  ]),
                  Row(children: [
                    Expanded(
                      flex: 5,
                      child: Padding(
                        padding: const EdgeInsets.fromLTRB(12, 12, 6, 6),
                        child: TextFormField(
                          controller: propKeyController,
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return 'Please enter property key';
                            }
                            return null;
                          },
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(),
                            hintText: 'Property key',
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 5,
                      child: Padding(
                        padding: const EdgeInsets.fromLTRB(6, 12, 12, 6),
                        child: TextFormField(
                          controller: propValueController,
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(),
                            hintText: 'Property value',
                          ),
                        ),
                      ),
                    ),
                  ]),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(6, 6, 6, 60),
                    child: Row(
                      children: [
                        Expanded(
                            flex: 5,
                            child: Padding(
                              padding: const EdgeInsets.all(6),
                              child: OutlinedButton(
                                child: const Padding(
                                  padding: EdgeInsets.symmetric(
                                      vertical: 18, horizontal: 12),
                                  child: Text(
                                    "Set Property",
                                    textAlign: TextAlign.center,
                                    textScaleFactor: 1.2,
                                  ),
                                ),
                                onPressed: () async {
                                  if (_userPropertySetUnsetFormKey.currentState!
                                      .validate()) {
                                    if (_propertyValue.isNotEmpty) {
                                      Map<String, Object> props = HashMap();
                                      props[_propertyKey] = _propertyValue;
                                      suprsend.user.set(props);
                                    } else {
                                      print(
                                          "Property Value must not be empty when calling set()!");
                                    }
                                  } else {
                                    print(
                                        "There are validation errors with your Property Key!");
                                  }
                                },
                              ),
                            )),
                        Expanded(
                            flex: 5,
                            child: Padding(
                              padding: const EdgeInsets.all(6),
                              child: OutlinedButton(
                                child: const Padding(
                                  padding: EdgeInsets.symmetric(
                                      vertical: 18, horizontal: 12),
                                  child: Text(
                                    "Unset Property",
                                    textAlign: TextAlign.center,
                                    textScaleFactor: 1.2,
                                  ),
                                ),
                                style: ButtonStyle(
                                    backgroundColor: MaterialStateProperty.all(
                                        Colors.blueAccent[600])),
                                onPressed: () {
                                  if (_userPropertySetUnsetFormKey.currentState!
                                      .validate()) {
                                    var list = [_propertyKey];
                                    suprsend.user.unSet(list);
                                  } else {
                                    print(
                                        "There are validation errors with your Property Value!");
                                  }
                                },
                              ),
                            ))
                      ],
                    ),
                  ),
                  Row(children: const [
                    Expanded(
                        flex: 10,
                        child: Padding(
                            padding: EdgeInsets.fromLTRB(14, 6, 12, 0),
                            child: Text(
                              "Mobile Number Set/Unset form",
                              textAlign: TextAlign.start,
                              textScaleFactor: 1.2,
                            ))),
                  ]),
                  Form(
                      key: _userMobileFormKey,
                      child: Column(mainAxisSize: MainAxisSize.max, children: [
                        Row(children: [
                          Expanded(
                            flex: 10,
                            child: Padding(
                              padding: const EdgeInsets.fromLTRB(12, 12, 6, 6),
                              child: TextFormField(
                                keyboardType: TextInputType.phone,
                                controller: propMobileNumberController,
                                validator: (value) {
                                  if (value == null || value.isEmpty) {
                                    return 'Please enter Mobile number';
                                  }
                                  String mobileInput =
                                      value.replaceAll(" ", "");
                                  int limit = 10;
                                  if (mobileInput.contains("+")) {
                                    limit = 14;
                                  }
                                  if (mobileInput.length > limit ||
                                      mobileInput.length < 10) {
                                    return 'Please enter a valid 10 digit Mobile number';
                                  }
                                  String digits =
                                      mobileInput.replaceAll("+", "");
                                  var number = double.tryParse(digits);
                                  if (number == null) {
                                    return 'Please enter a valid 10 digit Mobile number';
                                  }
                                  return null;
                                },
                                decoration: const InputDecoration(
                                  border: OutlineInputBorder(),
                                  hintText: 'Mobile number',
                                ),
                              ),
                            ),
                          ),
                        ]),
                        Padding(
                          padding: const EdgeInsets.fromLTRB(6, 6, 6, 6),
                          child: Row(
                            children: [
                              Expanded(
                                  flex: 5,
                                  child: Padding(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 6, vertical: 0),
                                    child: OutlinedButton(
                                      child: const Padding(
                                        padding: EdgeInsets.symmetric(
                                            vertical: 18, horizontal: 12),
                                        child: Text(
                                          "Set SMS Number",
                                          textAlign: TextAlign.center,
                                          textScaleFactor: 1.2,
                                        ),
                                      ),
                                      onPressed: () {
                                        var validationResult =
                                            _userMobileFormKey.currentState!
                                                .validate();
                                        log("_propertyMobileNumber == $_propertyMobileNumber");
                                        log("propMobileNumberController.text.toString() == ${propMobileNumberController.text.toString()}");
                                        if (validationResult) {
                                          if (_propertyMobileNumber
                                              .isNotEmpty) {
                                            String mobile =
                                                _propertyMobileNumber;
                                            if (!mobile.contains("+91")) {
                                              mobile =
                                                  "+91" + _propertyMobileNumber;
                                            }
                                            suprsend.user.setSms(mobile);
                                          } else {
                                            print(
                                                "Mobile number must not be empty when calling setSMS()!");
                                          }
                                        } else {
                                          print(
                                              "There are validation errors with your Property Mobile number!");
                                        }
                                      },
                                    ),
                                  )),
                              Expanded(
                                  flex: 5,
                                  child: Padding(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 6, vertical: 0),
                                    child: OutlinedButton(
                                      child: const Padding(
                                        padding: EdgeInsets.symmetric(
                                            vertical: 18, horizontal: 12),
                                        child: Text(
                                          "Unset SMS Number",
                                          textAlign: TextAlign.center,
                                          textScaleFactor: 1.2,
                                        ),
                                      ),
                                      onPressed: () {
                                        var validationResult =
                                            _userMobileFormKey.currentState!
                                                .validate();
                                        log("_propertyMobileNumber == $_propertyMobileNumber");
                                        log("propMobileNumberController.text.toString() == ${propMobileNumberController.text.toString()}");
                                        if (validationResult) {
                                          if (_propertyMobileNumber
                                              .isNotEmpty) {
                                            String mobile =
                                                _propertyMobileNumber;
                                            if (!mobile.contains("+91")) {
                                              mobile =
                                                  "+91" + _propertyMobileNumber;
                                            }
                                            suprsend.user.unSetSms(mobile);
                                          } else {
                                            print(
                                                "Mobile number must not be empty when calling unSetSMS()!");
                                          }
                                        } else {
                                          print(
                                              "There are validation errors with your Property Mobile number!");
                                        }
                                      },
                                    ),
                                  )),
                            ],
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.fromLTRB(6, 6, 6, 60),
                          child: Row(
                            children: [
                              Expanded(
                                  flex: 5,
                                  child: Padding(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 6, vertical: 0),
                                    child: OutlinedButton(
                                      child: const Padding(
                                        padding: EdgeInsets.symmetric(
                                            vertical: 18, horizontal: 12),
                                        child: Text(
                                          "Set Whatsapp Number",
                                          textAlign: TextAlign.center,
                                          textScaleFactor: 1.1,
                                        ),
                                      ),
                                      onPressed: () {
                                        var validationResult =
                                            _userMobileFormKey.currentState!
                                                .validate();
                                        log("_propertyMobileNumber == $_propertyMobileNumber");
                                        log("propMobileNumberController.text.toString() == ${propMobileNumberController.text.toString()}");
                                        if (validationResult) {
                                          if (_propertyMobileNumber
                                              .isNotEmpty) {
                                            String mobile =
                                                _propertyMobileNumber;
                                            if (!mobile.contains("+91")) {
                                              mobile =
                                                  "+91" + _propertyMobileNumber;
                                            }
                                            suprsend.user.setWhatsApp(mobile);
                                          } else {
                                            print(
                                                "Mobile number must not be empty when calling setWhatsApp()!");
                                          }
                                        } else {
                                          print(
                                              "There are validation errors with your Property Mobile number!");
                                        }
                                      },
                                    ),
                                  )),
                              Expanded(
                                  flex: 5,
                                  child: Padding(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 6, vertical: 0),
                                    child: OutlinedButton(
                                      child: const Padding(
                                        padding: EdgeInsets.symmetric(
                                            vertical: 18, horizontal: 12),
                                        child: Text(
                                          "Unset Whatsapp Number",
                                          textAlign: TextAlign.center,
                                          textScaleFactor: 1.1,
                                        ),
                                      ),
                                      onPressed: () {
                                        var validationResult =
                                            _userMobileFormKey.currentState!
                                                .validate();
                                        log("_propertyMobileNumber == $_propertyMobileNumber");
                                        log("propMobileNumberController.text.toString() == ${propMobileNumberController.text.toString()}");
                                        if (validationResult) {
                                          if (_propertyMobileNumber
                                              .isNotEmpty) {
                                            String mobile =
                                                _propertyMobileNumber;
                                            if (!mobile.contains("+91")) {
                                              mobile =
                                                  "+91" + _propertyMobileNumber;
                                            }
                                            suprsend.user.unSetWhatsApp(mobile);
                                          } else {
                                            print(
                                                "Mobile number must not be empty when calling unSetWhatsApp()!");
                                          }
                                        } else {
                                          print(
                                              "There are validation errors with your Property Mobile number!");
                                        }
                                      },
                                    ),
                                  )),
                            ],
                          ),
                        )
                      ])),
                  Row(children: const [
                    Expanded(
                        flex: 10,
                        child: Padding(
                            padding: EdgeInsets.fromLTRB(14, 6, 12, 0),
                            child: Text(
                              "Email ID Set/Unset form",
                              textAlign: TextAlign.start,
                              textScaleFactor: 1.2,
                            ))),
                  ]),
                  Form(
                      key: _userEmailFormKey,
                      child: Column(mainAxisSize: MainAxisSize.max, children: [
                        Row(children: [
                          Expanded(
                            flex: 10,
                            child: Padding(
                              padding: const EdgeInsets.fromLTRB(12, 12, 6, 6),
                              child: TextFormField(
                                keyboardType: TextInputType.emailAddress,
                                controller: propEmailController,
                                validator: (value) {
                                  if (value == null || value.isEmpty) {
                                    return 'Please enter email ID';
                                  }
                                  String emailInput = value.trim();

                                  if (!emailInput.contains("@")) {
                                    return 'Please enter a valid email ID';
                                  }
                                  if (!emailInput.contains(".")) {
                                    return 'Please enter a valid email ID';
                                  }
                                  return null;
                                },
                                decoration: const InputDecoration(
                                  border: OutlineInputBorder(),
                                  hintText: 'Email ID',
                                ),
                              ),
                            ),
                          ),
                        ]),
                        Padding(
                          padding: const EdgeInsets.fromLTRB(6, 6, 6, 60),
                          child: Row(
                            children: [
                              Expanded(
                                  flex: 5,
                                  child: Padding(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 6, vertical: 0),
                                    child: OutlinedButton(
                                      child: const Padding(
                                        padding: EdgeInsets.symmetric(
                                            vertical: 18, horizontal: 12),
                                        child: Text(
                                          "Set Email",
                                          textAlign: TextAlign.center,
                                          textScaleFactor: 1.2,
                                        ),
                                      ),
                                      onPressed: () {
                                        var validationResult = _userEmailFormKey
                                            .currentState!
                                            .validate();
                                        log("_propertyEmail == $_propertyEmail");
                                        log("propEmailController.text.toString() == ${propEmailController.text.toString()}");
                                        if (validationResult) {
                                          if (_propertyEmail.isNotEmpty) {
                                            suprsend.user
                                                .setEmail(_propertyEmail);
                                          } else {
                                            print(
                                                "Email must not be empty when calling setEmail()!");
                                          }
                                        } else {
                                          print(
                                              "There are validation errors with your Property Email!");
                                        }
                                      },
                                    ),
                                  )),
                              Expanded(
                                  flex: 5,
                                  child: Padding(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 6, vertical: 0),
                                    child: OutlinedButton(
                                      child: const Padding(
                                        padding: EdgeInsets.symmetric(
                                            vertical: 18, horizontal: 12),
                                        child: Text(
                                          "Unset Email",
                                          textAlign: TextAlign.center,
                                          textScaleFactor: 1.2,
                                        ),
                                      ),
                                      onPressed: () {
                                        var validationResult = _userEmailFormKey
                                            .currentState!
                                            .validate();
                                        log("_propertyEmail == $_propertyEmail");
                                        log("propEmailController.text.toString() == ${propEmailController.text.toString()}");
                                        if (validationResult) {
                                          if (_propertyEmail.isNotEmpty) {
                                            suprsend.user
                                                .unSetEmail(_propertyEmail);
                                          } else {
                                            print(
                                                "Email must not be empty when calling unSetEmail()!");
                                          }
                                        } else {
                                          print(
                                              "There are validation errors with your Property Email!");
                                        }
                                      },
                                    ),
                                  )),
                            ],
                          ),
                        ),
                      ])),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(6, 6, 6, 0),
                    child: Row(
                      children: [
                        Expanded(
                            flex: 10,
                            child: Padding(
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 6, vertical: 0),
                              child: OutlinedButton(
                                child: const Padding(
                                  padding: EdgeInsets.symmetric(
                                      vertical: 18, horizontal: 12),
                                  child: Text(
                                    "Clear All Inputs",
                                    textAlign: TextAlign.center,
                                    textScaleFactor: 1.2,
                                  ),
                                ),
                                onPressed: () {
                                  propDistinctIdController.clear();
                                  propKeyController.clear();
                                  propValueController.clear();
                                  propMobileNumberController.clear();
                                },
                              ),
                            )),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(6, 6, 6, 60),
                    child: Row(
                      children: [
                        Expanded(
                            flex: 10,
                            child: Padding(
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 6, vertical: 0),
                              child: OutlinedButton(
                                child: const Padding(
                                  padding: EdgeInsets.symmetric(
                                      vertical: 18, horizontal: 12),
                                  child: Text(
                                    "Logout",
                                    textAlign: TextAlign.center,
                                    textScaleFactor: 1.2,
                                  ),
                                ),
                                onPressed: () {
                                  setState(() {
                                    _userId = "";
                                    _subsId = "";
                                  });
                                  suprsend
                                      .unSetSuperProperty("Platform_Version");
                                  suprsend.unSetSuperProperty("User_ID");
                                  suprsend.flush();
                                  suprsend.reset();
                                },
                              ),
                            )),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(6, 6, 6, 60),
                    child: Row(
                      children: const [InboxBell()],
                    ),
                  ),
                ],
              ),
            ),
          ),
        )));
  }

  [@override](/user/override)
  void dispose() {
    propKeyController.dispose();
    propValueController.dispose();
    propDistinctIdController.dispose();
    propMobileNumberController.dispose();
    propEmailController.dispose();
    _linkSub.cancel();
    super.dispose();
  }
}

class InboxBell extends HookWidget {
  const InboxBell({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    final bellData = useBell();
    print("rerendered bell");
    return Expanded(
        flex: 10,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 0),
          child: OutlinedButton(
            child: Text("Unread ${bellData["unSeenCount"]} notifications"),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => const InboxNotifications()),
              );
              // Navigator.push(
              //   context,
              //   MaterialPageRoute(
              //     builder: (newcontext) =>
              //         BlocProvider<SuprSendStoreCubit>.value(
              //       value: BlocProvider.of<SuprSendStoreCubit>(context),
              //       child: const InboxNotifications(),
              //     ),
              //   ),
              // );
            },
          ),
        ));
  }
}

class InboxNotifications extends HookWidget {
  const InboxNotifications({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    final notifData = useNotifications();

    useNewNotificationListener((data) {
      print("NEW DATA ${data.length}");
      const snackBar = SnackBar(
        content: Text('Got new notifications'),
      );
      ScaffoldMessenger.of(context).showSnackBar(snackBar);
    });

    useEffect(() {
      notifData["markAllSeen"]();
    }, []);

    if (notifData["notifications"] != null && notifData["notifications"].length > 0) {
      return Scaffold(
          appBar: AppBar(
            title: const Text('Notifications'),
          ),
          body: ListView.builder(
            itemCount: notifData["notifications"].length,
            scrollDirection: Axis.vertical,
            shrinkWrap: true,
            physics: const ScrollPhysics(),
            itemBuilder: (context, index) {
              final notifMessage = notifData["notifications"][index];
              return ListTile(
                title: Text(
                    '${notifMessage["message"]["header"]} ${notifMessage["seen_on"] != null ? '' : "*"}'),
                subtitle: Text('${notifMessage["message"]["text"]}'),
                onTap: () {
                  notifData["markClicked"](notifMessage["n_id"]);
                },
              );
            },
          ));
    } else {
      return Scaffold(
          appBar: AppBar(
            title: const Text('Notifications'),
          ),
          body: const Text("NO DATA", textDirection: TextDirection.ltr));
    }
  }
}

更多关于Flutter数据传输与发送插件suprsend_flutter_sdk的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据传输与发送插件suprsend_flutter_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


suprsend_flutter_sdk 是一个用于在 Flutter 应用中集成 SuprSend 服务的插件。SuprSend 是一个通知基础设施平台,允许开发者轻松地发送通知到多种渠道(如电子邮件、短信、推送通知等)。

以下是如何在 Flutter 项目中使用 suprsend_flutter_sdk 的基本步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 suprsend_flutter_sdk 依赖:

dependencies:
  flutter:
    sdk: flutter
  suprsend_flutter_sdk: ^1.0.0  # 请使用最新版本

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

2. 初始化 SDK

在应用的入口文件(例如 main.dart)中初始化 SDK:

import 'package:suprsend_flutter_sdk/suprsend_flutter_sdk.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 SuprSend SDK
  SuprsendFlutterSdk.initialize(
    apiKey: 'YOUR_API_KEY',
    apiSecret: 'YOUR_API_SECRET',
    workspace: 'YOUR_WORKSPACE',
  );

  runApp(MyApp());
}

请将 YOUR_API_KEY、YOUR_API_SECRET 和 YOUR_WORKSPACE 替换为你在 SuprSend 平台上获得的实际值。

3. 设置用户信息

在用户登录或注册后,你可以设置用户的相关信息,以便 SuprSend 能够正确地将通知发送给用户:

SuprsendFlutterSdk.identify(
  distinctId: 'USER_ID', // 用户的唯一标识符
  properties: {
    'email': 'user@example.com',
    'phone': '+1234567890',
    'name': 'John Doe',
  },
);

4. 发送通知

你可以使用 track 方法来发送事件通知:

SuprsendFlutterSdk.track(
  eventName: 'EVENT_NAME', // 事件名称
  properties: {
    'property1': 'value1',
    'property2': 'value2',
  },
);

5. 管理用户订阅

你可以管理用户的通知订阅状态:

// 订阅用户到某个渠道
SuprsendFlutterSdk.subscribe(
  channel: 'email', // 渠道类型,如 'email', 'sms', 'push' 等
  value: 'user@example.com', // 用户的值,如电子邮件地址或电话号码
);

// 取消用户订阅某个渠道
SuprsendFlutterSdk.unsubscribe(
  channel: 'email',
  value: 'user@example.com',
);

6. 处理推送通知

如果你需要在应用中处理推送通知,可以集成 firebase_messaging 插件来处理推送通知的接收和显示。

7. 调试和日志

你可以在初始化 SDK 时启用调试模式,以便在开发过程中查看日志:

SuprsendFlutterSdk.initialize(
  apiKey: 'YOUR_API_KEY',
  apiSecret: 'YOUR_API_SECRET',
  workspace: 'YOUR_WORKSPACE',
  debug: true, // 启用调试模式
);
回到顶部