Flutter功能扩展插件flutter_plugin_engagelab的使用

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

Flutter功能扩展插件flutter_plugin_engagelab的使用

Setup

在项目的 pubspec.yaml 文件中添加依赖:

dependencies:
  flutter_plugin_engagelab:
    git:
      url: git://github.com/DevEngageLab/push-flutter-plugin.git
      ref: main

或者直接通过 pub 添加:

dependencies:
  flutter_plugin_engagelab: 1.2.4

配置

Android

/android/app/build.gradle 文件中添加以下代码:

android {
  ...
  defaultConfig {
    applicationId "Replace with your own application ID"
    ...
    manifestPlaceholders = [
      ENGAGELAB_PRIVATES_APPKEY: "your appkey",
      ENGAGELAB_PRIVATES_CHANNEL: "developer",
      ENGAGELAB_PRIVATES_PROCESS: ":remote",
      XIAOMI_APPID: "", // 填写小米厂商的MI-appid,如果不存在则留空
      XIAOMI_APPKEY: "", // 填写小米厂商的MI-appkey,如果不存在则留空
      MEIZU_APPID: "", // 填写魅族厂商的MZ-appid,如果不存在则留空
      MEIZU_APPKEY: "", // 填写魅族厂商的MZ-appkey,如果不存在则留空
      OPPO_APPID: "", // 填写OPPO厂商的OP-appid,如果不存在则留空
      OPPO_APPKEY: "", // 填写OPPO厂商的OP-appkey,如果不存在则留空
      OPPO_APPSECRET: "", // 填写OPPO厂商的OP-appsecret,如果不存在则留空
      VIVO_APPID: "", // 填写VIVO厂商的appid,如果不存在则留空
      VIVO_APPKEY: "", // 填写VIVO厂商的appkey,如果不存在则留空
      HONOR_APPID: "", // 填写Honor厂商的appid,如果不存在则留空
      APP_TCP_SSL: "", // 是否启用TCP连接加密,填写true表示加密,否则表示不加密。对于此数据生效,需要在AndroidManifest.xml中添加android:name="com.engagelab.privates.flutter_plugin_engagelab.MTApplication"到application中,或者让MainApplication继承MTApplication。
      APP_DEBUG: "", // 填写true表示调试模式,否则表示非调试模式。对于此数据生效,需要在AndroidManifest.xml中添加android:name="com.engagelab.privates.flutter_plugin_engagelab.MTApplication"到application中,或者继承此对象。
      COUNTRY_CODE: "" // 用于测试,可以留空。对于此数据生效,需要在AndroidManifest.xml中添加android:name="com.engagelab.privates.flutter_plugin_engagelab.MTApplication"到application中,或者继承此对象。
    ]
  }
}
iOS

在Xcode 8之后,需要点击推送选项:TARGETS -> Capabilities -> Push Notification 并将其设置为开启。

使用

在项目中导入插件:

import 'package:flutter_plugin_engagelab/flutter_plugin_engagelab.dart';

API

注意:FlutterPluginEngagelab.init 需要首先被调用以初始化插件,确保其他功能正常工作。

示例代码如下:

import 'dart:io';

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

import 'package:flutter/services.dart';
import 'package:flutter_plugin_engagelab/flutter_plugin_engagelab.dart';

void main() {
  runApp(const 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 _event_name = 'Unknown';
  String _event_data = 'Unknown';

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

  // 平台消息是异步的,所以我们初始化在一个异步方法中。
  Future<void> initPlatformState() async {
    FlutterPluginEngagelab.addEventHandler(
        onMTCommonReceiver: (Map<String, dynamic> message) async {
      FlutterPluginEngagelab.printMy("flutter onMTCommonReceiver: $message");
      String event_name = message["event_name"];
      String event_data = message["event_data"];
      FlutterPluginEngagelab.printMy(
          "flutter onMTCommonReceiver event_name: " + event_name);
      FlutterPluginEngagelab.printMy(
          "flutter onMTCommonReceiver event_data: " + event_data);
      setState(() {
        _event_name = "$event_name";
        _event_data = "$event_data";
        // debugLable = "flutter onMTCommonReceiver: $message";
        if (Comparable.compare(event_name, "onConnectStatus") == 0 ||
            Comparable.compare(event_name, "networkDidLogin") == 0) {
          FlutterPluginEngagelab.getRegistrationId().then((rid) {
            FlutterPluginEngagelab.printMy(
                "flutter get registration id : $rid");
            setState(() {
              _platformVersion = "$rid";
            });
            // 设置用户语言
            // FlutterPluginEngagelab.setUserLanguage("zh-Hans-CN");
          });
        }
      });
    });
    FlutterPluginEngagelab.configDebugMode(true);
    if (Platform.isIOS) {
      FlutterPluginEngagelab.initIos(
        appKey: "fcc545917674d6f06c141704", // 5645a6e0c6ef00bb71facf21
        channel: "testChannel",
      );
      FlutterPluginEngagelab.checkNotificationAuthorizationIos();
    } else if (Platform.isAndroid) {
      FlutterPluginEngagelab.initAndroid();
    }

    String platformVersion = "";
    // 平台消息可能会失败,所以我们使用一个try/catch来处理PlatformException。
    // 我们也处理了消息可能返回null的情况。
    FlutterPluginEngagelab.getRegistrationId().then((rid) {
      FlutterPluginEngagelab.printMy("flutter get registration id : $rid");
      setState(() {
        _platformVersion = "$rid";
      });
    });

    // 如果页面进入离开,请配置pageEnterTo和pageLeave函数,参数为页面名。
    FlutterPluginEngagelab.pageEnterTo(
        "HomePage"); // 在离开页面的时候请调用 FlutterPluginEngagelab.pageLeave("HomePage");

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: [
              Container(
                margin: const EdgeInsets.fromLTRB(10, 10, 10, 10),
                color: Colors.brown,
                child: Text('RID: $_platformVersion\n'
                    'EVENT NAME: $_event_name\n'
                    'EVENT DATA: $_event_data\n'),
                width: 350,
                height: 100,
              ),
              Row(children: <Widget>[
                const Text(" "),
                CustomButton(
                    title: "发送本地通知",
                    onPressed: () {
                      // 三秒后触发本地推送
                      var fireDate = DateTime.fromMillisecondsSinceEpoch(
                          DateTime.now().millisecondsSinceEpoch + 3000);
                      var localNotification = LocalNotification(
                          id: 234,
                          title: 'fadsfa',
                          content: 'fdas',
                          fireTime: fireDate,
                          subtitle: 'fasf',
                          category: 'local',
                          priority: 2,
                          badge: 5,
                          extra: {"fa": "0"});
                      FlutterPluginEngagelab.sendLocalNotification(
                              localNotification)
                          .then((res) {
                        // setState(() {
                        //   debugLable = res;
                        // });
                      });
                    }),
              ]),
              Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    const Text(" "),
                    CustomButton(
                        title: "updateTags",
                        onPressed: () {
                          FlutterPluginEngagelab.updateTags({
                            "sequence": 1,
                            "tags": ["lala", "haha"]
                          });
                        }),
                    const Text(" "),
                    CustomButton(
                        title: "addTags",
                        onPressed: () {
                          FlutterPluginEngagelab.addTags({
                            "sequence": 2,
                            "tags": ["lala", "haha"]
                          });
                        }),
                    const Text(" "),
                    CustomButton(
                        title: "deleteTags",
                        onPressed: () {
                          FlutterPluginEngagelab.deleteTags({
                            "sequence": 3,
                            "tags": ["lala", "haha"]
                          });
                        }),
                  ]),
              Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    const Text(" "),
                    CustomButton(
                        title: "getAllTags",
                        onPressed: () {
                          FlutterPluginEngagelab.queryAllTag(4);
                        }),
                    const Text(" "),
                    CustomButton(
                        title: "cleanTags",
                        onPressed: () {
                          FlutterPluginEngagelab.deleteAllTag(5);
                        }),
                    const Text(" "),
                    CustomButton(
                        title: "queryTag",
                        onPressed: () {
                          FlutterPluginEngagelab.queryTag(
                              {"sequence": 6, "tag": "lala"});
                        }),
                  ]),
              Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    const Text(" "),
                    CustomButton(
                        title: "setAlias",
                        onPressed: () {
                          FlutterPluginEngagelab.setAlias(7, "thealias11");
                        }),
                    const Text(" "),
                    CustomButton(
                        title: "deleteAlias",
                        onPressed: () {
                          FlutterPluginEngagelab.clearAlias(8);
                        }),
                    const Text(" "),
                    CustomButton(
                        title: "getAlias",
                        onPressed: () {
                          FlutterPluginEngagelab.getAlias(9);
                        }),
                  ]),
            ],
          ),
        ),
      ),
    );
  }
}

/// 封装控件
class CustomButton extends StatelessWidget {
  final VoidCallback? onPressed;
  final String? title;

  const CustomButton({[@required](/user/required) this.onPressed, [@required](/user/required) this.title});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return TextButton(
      onPressed: onPressed,
      child: Text("$title"),
      style: ButtonStyle(
        foregroundColor: MaterialStateProperty.all(Colors.white),
        overlayColor: MaterialStateProperty.all(const Color(0xff888888)),
        backgroundColor: MaterialStateProperty.all(const Color(0xff585858)),
        padding:
            MaterialStateProperty.all(const EdgeInsets.fromLTRB(10, 5, 10, 5)),
      ),
    );
  }
}

更多关于Flutter功能扩展插件flutter_plugin_engagelab的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter功能扩展插件flutter_plugin_engagelab的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用 flutter_plugin_engagelab 插件的示例代码。请注意,flutter_plugin_engagelab 并非一个官方或广泛认知的 Flutter 插件,这里假设它是一个用于特定功能扩展的自定义插件。为了演示,我们将创建一个基本的 Flutter 应用,并假设 flutter_plugin_engagelab 提供了一些功能,比如显示一个自定义的欢迎消息。

首先,确保在 pubspec.yaml 文件中添加了对 flutter_plugin_engagelab 的依赖(如果它是一个可用的 pub 包):

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

然后,运行 flutter pub get 来获取依赖项。

接下来,在你的 Flutter 应用中使用这个插件。下面是一个简单的示例:

import 'package:flutter/material.dart';
import 'package:flutter_plugin_engagelab/flutter_plugin_engagelab.dart';  // 假设这是插件的导入路径

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Plugin Engagelab Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String? welcomeMessage;

  @override
  void initState() {
    super.initState();
    // 假设插件有一个方法来获取欢迎消息
    _getWelcomeMessage();
  }

  Future<void> _getWelcomeMessage() async {
    String? message;
    try {
      // 调用插件的方法
      message = await FlutterPluginEngagelab.getWelcomeMessage();
      setState(() {
        welcomeMessage = message;
      });
    } catch (e) {
      print('Error fetching welcome message: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Plugin Engagelab Demo'),
      ),
      body: Center(
        child: welcomeMessage != null
            ? Text(
                'Welcome Message: $welcomeMessage',
                style: TextStyle(fontSize: 24),
              )
            : CircularProgressIndicator(),
      ),
    );
  }
}

在这个示例中,我们假设 flutter_plugin_engagelab 插件有一个静态方法 getWelcomeMessage(),它返回一个欢迎消息。在 MyHomePage 类的 initState 方法中,我们调用这个方法,并在获取到消息后更新 UI。

注意

  1. 实际的插件使用可能会根据插件的功能和 API 有所不同。你需要参考插件的官方文档来了解具体的 API 使用方法。
  2. 如果 flutter_plugin_engagelab 不是一个公开的 pub 包,你可能需要从本地路径或 Git 仓库中添加依赖,或者使用其他方式将其集成到你的 Flutter 项目中。
  3. 如果插件包含原生代码(如 Android 的 Kotlin/Java 或 iOS 的 Swift/Objective-C),你还需要在相应的原生项目中进行一些配置。这通常包括在 android/app/src/main/AndroidManifest.xml 中声明权限,或在 iOS 的 Info.plist 中添加配置等。

由于 flutter_plugin_engagelab 并非一个已知的标准插件,以上代码仅作为假设性示例。实际使用时,请务必参考插件的官方文档和示例代码。

回到顶部