Flutter推送通知插件karte_notification的使用

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

Flutter推送通知插件karte_notification的使用

KARTE Notification 插件用于在 Flutter 应用程序中实现推送通知功能。它支持 Android 和 iOS 平台。

文档

开发指南可以在以下位置找到:

许可证

Flutter KARTE Notification 插件是在 Apache 2.0 许可证下发布的。

你的使用受 KARTE 使用条款 管理。

示例代码

以下是使用 karte_notification 插件的基本示例代码:

import 'dart:async';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:karte_core/karte_core.dart';
import 'package:karte_notification/karte_notification.dart' as krt;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

Future<dynamic> myBackgroundMessageHandler(RemoteMessage message) async {
  // 当仅在后台接收到通知时调用
  print('myBackgroundMessageHandler $message');
  var karteNotification = await krt.Notification.create(message);
  print("karte notification: $karteNotification");
  if (karteNotification != null) {
    karteNotification.handleForAndroid();
  }
}

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

class _MyAppState extends State<MyApp> {
  String _homeScreenText = "等待令牌...";
  String _logText = "";
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;

  void updateState({String? log, String? token}) {
    if (!mounted) return;
    setState(() {
      if (log != null) _logText += log;
      if (token != null) _homeScreenText = "推送消息令牌: $token";
    });
  }

  void checkInitialMessage() async {
    RemoteMessage? message = await FirebaseMessaging.instance.getInitialMessage();
    // 当应用程序通过点击通知启动时调用
    print("checkInitialMessage: $message");
    updateState(log: "\nonLaunch");
    if (message == null) return;
    var karteNotification = await krt.Notification.create(message);
    print("karte notification: $karteNotification");
    if (karteNotification != null) {
      karteNotification.handleForIOS();
    }
  }

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

    checkInitialMessage();
    FirebaseMessaging.onBackgroundMessage(myBackgroundMessageHandler);
    FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
      // 当在前台接收到通知时调用
      print("onMessage: $message");
      updateState(log: "\nonMessage");
      var karteNotification = await krt.Notification.create(message);
      print("karte notification: $karteNotification");
      if (karteNotification != null) {
        karteNotification.handleForAndroid();
      }
    });
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async {
      // 当通过点击通知恢复应用程序时调用
      print("onMessageOpenedApp: $message");
      updateState(log: "\nonMessageOpenedApp");
      var karteNotification = await krt.Notification.create(message);
      print("karte notification: $karteNotification");
      if (karteNotification != null) {
        karteNotification.handleForIOS();
      }
    });
    _firebaseMessaging
        .requestPermission(
            alert: true, badge: true, provisional: true, sound: true)
        .then((NotificationSettings value) {
      print("设置已注册: $value");
    });
    _firebaseMessaging.onTokenRefresh.listen((String token) {
      print("onTokenRefreshed: $token");
      krt.Notification.registerFCMToken(token);
      updateState(token: token);
    });
    _firebaseMessaging.getToken().then((String? token) {
      if (token == null) return;
      krt.Notification.registerFCMToken(token);
      updateState(token: token);
      print(_homeScreenText);
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('KARTE Notification 示例应用'),
        ),
        body: Center(
          child: Column(
              children: [
                Text(_homeScreenText),
                ElevatedButton(
                  onPressed: () {
                    Tracker.view("push_text");
                  },
                  child: Text("查看"),
                ),
                Text(_logText),
              ]),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用karte_notification插件来实现推送通知的示例代码。这个插件通常用于集成Karte的推送通知服务。请确保你已经按照官方文档完成了必要的配置,比如创建Karte项目并获取API密钥。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加karte_notification依赖:

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

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

2. 初始化Karte和推送通知

在你的Flutter应用的主入口文件(通常是main.dart)中,初始化Karte和推送通知服务:

import 'package:flutter/material.dart';
import 'package:karte_core/karte_core.dart';
import 'package:karte_notification/karte_notification.dart';

void main() {
  // 初始化Karte
  Karte.initialize(apiKey: '你的API密钥');

  // 初始化推送通知
  KarteNotification.initialize();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Karte Notification 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 Karte Notification Demo'),
      ),
      body: Center(
        child: Text('推送通知已初始化!'),
      ),
    );
  }
}

3. 处理推送通知事件

你可能想要处理推送通知到达、点击等事件。你可以通过监听KarteNotification的事件来实现:

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();

    // 监听推送通知到达事件
    KarteNotification.onNotificationReceived.listen((message) {
      print('Notification received: $message');
      // 你可以在这里更新UI或者做其他处理
    });

    // 监听推送通知点击事件
    KarteNotification.onNotificationOpened.listen((message) {
      print('Notification opened: $message');
      // 你可以在这里处理点击事件,比如导航到特定页面
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Karte Notification Demo'),
      ),
      body: Center(
        child: Text('推送通知已初始化!'),
      ),
    );
  }

  @override
  void dispose() {
    // 取消监听
    KarteNotification.onNotificationReceived.cancel();
    KarteNotification.onNotificationOpened.cancel();
    super.dispose();
  }
}

4. 发送测试推送通知

在Karte的控制台中,你可以发送测试推送通知到你的设备,以确保一切正常工作。通常,你需要设备的FCM(Firebase Cloud Messaging)注册ID,这个ID会在设备成功注册推送服务后由Karte SDK自动管理。

注意事项

  • 确保你的应用已经正确配置了Firebase项目,并且已经在Firebase控制台中添加了相应的FCM配置。
  • 根据Karte的官方文档,你可能需要在你的AndroidManifest.xmliOS项目中添加一些必要的配置。
  • 测试时请确保你的应用处于后台或关闭状态,以验证推送通知的正确性。

这个示例代码提供了一个基本的框架,你可以根据自己的需求进一步扩展和处理推送通知。

回到顶部