Flutter消息推送插件cleverpush_flutter的使用

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

Flutter消息推送插件cleverpush_flutter的使用

文档

详细文档请参阅 CleverPush Flutter SDK 官方文档


以下是一个完整的示例代码,展示了如何在Flutter应用中使用cleverpush_flutter插件进行消息推送。

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

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _debugLabelString = "";

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

  Future<void> initPlatformState() async {
    if (!mounted) return;

    CleverPush.shared.setShowNotificationsInForeground(false);
    CleverPush.shared.enableDevelopmentMode();

    // CleverPush Channel ID
    await CleverPush.shared.init("CHANNEL_ID", true);

    CleverPush.shared
        .setNotificationReceivedHandler((CPNotificationReceivedResult result) {
      this.setState(() {
        _debugLabelString =
            "通知已接收: \n${result.notification!.jsonRepresentation().replaceAll("\\n", "\n")}";
      });
    });

    CleverPush.shared
        .setNotificationOpenedHandler((CPNotificationOpenedResult result) {
      this.setState(() {
        _debugLabelString =
            "通知已打开: \n${result.notification!.jsonRepresentation().replaceAll("\\n", "\n")}";
      });
    });

    CleverPush.shared.setSubscribedHandler((subscriptionId) {
      this.setState(() {
        _debugLabelString = "已订阅: " + subscriptionId!;
      });

      print("已订阅: $subscriptionId");
    });

    CleverPush.shared.enableAppBanners();

    CleverPush.shared.setAppBannerShownHandler((CPAppBanner appBanner) {
      this.setState(() {
        _debugLabelString = "APP BANNER 已显示: " + appBanner.name!;
      });
    });

    CleverPush.shared.setBrandingColor("#ff0000");

    CleverPush.shared.setChatUrlOpenedHandler((url) {
      Widget continueButton = TextButton(
        child: Text("确定"),
        onPressed: () => Navigator.pop(context, '确定'),
      );
      showDialog<String>(
        context: context,
        builder: (BuildContext context) => AlertDialog(
          title: const Text('聊天URL已打开'),
          content: Text(url),
          actions: <Widget>[
            continueButton,
          ],
        ),
      );
    });
  }

  void _handleSubscribe() async {
    print("请求权限");
    var id = await CleverPush.shared.subscribe();
    print("已订阅: $id");
  }

  void _handleUnsubscribe() {
    CleverPush.shared.unsubscribe();
  }

  void _handleIsSubscribed() {
    CleverPush.shared.isSubscribed().then((status) {
      this.setState(() {
        _debugLabelString = status.toString();
      });
    });
  }

  void _handleAreNotificationsEnabled() {
    CleverPush.shared.areNotificationsEnabled().then((status) {
      this.setState(() {
        _debugLabelString = status.toString();
      });
    });
  }

  void _handleTopicsDialog() {
    CleverPush.shared.showTopicsDialog();
  }

  void _getNotifications() async {
    List<CPNotification> notifications = await CleverPush.shared.getNotifications();
    if (notifications.isNotEmpty) {
      print("获取通知: " + notifications[0].jsonRepresentation());
    }
    this.setState(() {
      _debugLabelString = notifications.length.toString();
    });
  }

  void _getNotificationsWithApi() async {
    bool combineWithApi = true;
    List<CPNotification> remoteNotifications =
        await CleverPush.shared.getNotificationsWithApi(combineWithApi);
    if (remoteNotifications.isNotEmpty) {
      print("通过API获取通知: " + remoteNotifications[0].jsonRepresentation());
    }
    this.setState(() {
      _debugLabelString = remoteNotifications.length.toString();
    });
  }

  void _getSubscriptionTopics() async {
    var topicIds = await CleverPush.shared.getSubscriptionTopics();
    String topicIdsString = "";
    for (var i = 0; i < topicIds.length; i++) {
      if (topicIdsString.isEmpty) {
        topicIdsString = topicIds[i];
      } else {
        topicIdsString = topicIdsString + "," + topicIds[i];
      }
    }
    this.setState(() {
      _debugLabelString = topicIdsString;
    });
  }

  void _setSubscriptionTopics() {
    List<String> topics = ['hello', 'world'];
    CleverPush.shared.setSubscriptionTopics(topics);
  }

  void _getAvailableTopics() async {
    var topicIds = await CleverPush.shared.getAvailableTopics();
    if (topicIds.isNotEmpty) {
      print(topicIds[0]);
    }
    this.setState(() {
      _debugLabelString = topicIds.length.toString();
    });
  }

  void _getSubscriptionTags() async {
    var tagIds = await CleverPush.shared.getSubscriptionTags();
    String tagIdsString = "";
    for (var i = 0; i < tagIds.length; i++) {
      if (tagIdsString.isEmpty) {
        tagIdsString = tagIds[i];
      } else {
        tagIdsString = tagIdsString + "," + tagIds[i];
      }
    }
    this.setState(() {
      _debugLabelString = tagIdsString;
    });
  }

  void _addSubscriptionTag() {
    CleverPush.shared.addSubscriptionTag('TAG_ID');
  }

  void _addSubscriptionTags() {
    List<String> tagIds = ['TAG_ID1', 'TAG_ID2'];
    CleverPush.shared.addSubscriptionTags(tagIds);
  }

  void _removeSubscriptionTag() {
    CleverPush.shared.removeSubscriptionTag('TAG_ID');
  }

  void _removeSubscriptionTags() {
    List<String> tagIds = ['TAG_ID1', 'TAG_ID2'];
    CleverPush.shared.removeSubscriptionTags(tagIds);
  }

  void _getAvailableTags() async {
    var tagIds = await CleverPush.shared.getAvailableTags();
    if (tagIds.isNotEmpty) {
      print(tagIds[0]);
    }
    this.setState(() {
      _debugLabelString = tagIds.length.toString();
    });
  }

  void _trackEvent() async {
    CleverPush.shared.trackEvent("EVENT_NAME");
  }

  void _triggerFollowUpEvent() async {
    CleverPush.shared.triggerFollowUpEvent("EVENT_NAME", {
      "property_1": "value",
    });
  }

  void _pushSubscriptionAttributeValue() async {
    CleverPush.shared.pushSubscriptionAttributeValue("ATTRIBUTE_KEY","ATTRIBUTE_VALUE");
  }

  void _pullSubscriptionAttributeValue() async {
    CleverPush.shared.pullSubscriptionAttributeValue("ATTRIBUTE_KEY","ATTRIBUTE_VALUE");
  }

  void _showAppBanner() async {
    CleverPush.shared.showAppBanner("APP_BANNER_ID");
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return new MaterialApp(
      initialRoute: '/',
      routes: <String, WidgetBuilder>{
        '/': (BuildContext context) {
          return new Scaffold(
            appBar: new AppBar(
              title: const Text('CleverPush Flutter'),
              backgroundColor: Color.fromARGB(255, 33, 33, 33),
            ),
            body: Container(
              padding: EdgeInsets.all(10.0),
              child: SingleChildScrollView(
                child: new Table(
                  children: [
                    new TableRow(children: [
                      new Container(
                        child: new Text(_debugLabelString),
                        alignment: Alignment.center,
                      )
                    ]),
                    new TableRow(children: [
                      Container(
                        height: 8.0,
                      )
                    ]),
                    new TableRow(children: [
                      new CleverPushButton("显示聊天视图", () {
                        Navigator.pushNamed(context, '/chat');
                      }, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton("订阅", _handleSubscribe, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "取消订阅", _handleUnsubscribe, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "是否已订阅?", _handleIsSubscribed, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "通知是否启用?", _handleAreNotificationsEnabled, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "显示主题对话框", _handleTopicsDialog, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "获取通知", _getNotifications, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton("通过API获取通知",
                          _getNotificationsWithApi, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "获取订阅主题", _getSubscriptionTopics, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "设置订阅主题", _setSubscriptionTopics, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "获取可用主题", _getAvailableTopics, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "获取订阅标签", _getSubscriptionTags, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "添加订阅标签", _addSubscriptionTag, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "移除订阅标签", _removeSubscriptionTag, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "添加多个订阅标签", _addSubscriptionTags, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "移除多个订阅标签", _removeSubscriptionTags, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "获取可用标签", _getAvailableTags, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "跟踪事件", _trackEvent, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "显示APP横幅", _showAppBanner, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "跟踪后续事件", _triggerFollowUpEvent, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "推送订阅属性值", _pushSubscriptionAttributeValue, true)
                    ]),
                    new TableRow(children: [
                      new CleverPushButton(
                          "拉取订阅属性值", _pullSubscriptionAttributeValue, true)
                    ]),
                  ],
                ),
              ),
            ),
          );
        },
        '/chat': (BuildContext context) {
          return new Scaffold(
            appBar: AppBar(
              title: const Text('聊天视图'),
            ),
            body: new Container(
              child: CleverPushChatView(
                
              ),
            ),
          );
        },
      },
    );
  }
}

typedef void OnButtonPressed();

class CleverPushButton extends StatefulWidget {
  final String title;
  final OnButtonPressed onPressed;
  final bool enabled;

  CleverPushButton(this.title, this.onPressed, this.enabled);

  State<StatefulWidget> createState() => new CleverPushButtonState();
}

class CleverPushButtonState extends State<CleverPushButton> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return new Table(
      children: [
        new TableRow(children: [
          new TextButton(
            child: new Text(widget.title),
            onPressed: widget.enabled ? widget.onPressed : null,
          )
        ]),
        new TableRow(children: [
          Container(
            height: 8.0,
          )
        ]),
      ],
    );
  }
}

更多关于Flutter消息推送插件cleverpush_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter消息推送插件cleverpush_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中使用cleverpush_flutter插件进行消息推送的示例代码。这个示例将展示如何配置插件、初始化推送服务以及处理接收到的推送消息。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加cleverpush_flutter依赖:

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

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

2. 配置CleverPush

在Flutter应用的main.dart文件中,你需要配置并初始化CleverPush服务。

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  // 初始化CleverPush
  CleverPush.init(
    appId: '你的AppID', // 替换为你的CleverPush App ID
    clientKey: '你的ClientKey', // 替换为你的CleverPush Client Key
    onNotificationReceived: (Map<String, dynamic> message) {
      // 处理接收到的推送消息
      print('Received notification: $message');
    },
    onNotificationOpened: (Map<String, dynamic> message) {
      // 处理用户点击推送消息后的操作
      print('Opened notification: $message');
    },
  );

  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 StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo Home Page'),
      ),
      body: Center(
        child: Text('Check the console for notification logs.'),
      ),
    );
  }
}

3. 处理推送消息

在上面的代码中,我们使用了CleverPush.init方法来初始化CleverPush服务,并传递了onNotificationReceivedonNotificationOpened回调函数来处理接收到的推送消息和用户点击推送消息后的操作。

  • onNotificationReceived:当应用在前台时接收到推送消息时调用。
  • onNotificationOpened:当用户点击推送消息打开应用时调用。

4. 运行应用

确保你的Flutter环境已经正确配置,并且你的设备或模拟器已经连接到开发环境。然后运行应用:

flutter run

现在,你的Flutter应用应该能够接收并处理来自CleverPush的推送消息了。

注意事项

  1. 权限配置:确保在AndroidManifest.xmlInfo.plist文件中配置了必要的推送权限。
  2. 后台处理:对于需要在后台处理推送消息的应用,可能还需要在原生代码中进行额外的配置。

这个示例代码提供了一个基本的框架,你可以根据自己的需求进一步扩展和定制。

回到顶部