Flutter推送通知插件pushportal_package的使用

Flutter推送通知插件pushportal_package的使用

pushportal_package 是一个用于实现 iOS 和 Android 应用推送通知功能的 Flutter 插件。本文将详细介绍如何初始化该插件并使用其提供的功能。


初始化插件

在使用 pushportal_package 之前,需要调用 initializeApp 方法进行初始化。以下是初始化的示例代码:

await PushPortal.instance.initializeApp(
  username: 'username',       // 用户名
  password: 'password',       // 密码
  serviceLog: true,           // 是否开启服务日志
);

注册回调函数

插件提供了多种回调函数,用于处理不同的推送通知事件。以下是一些常用的回调函数注册示例:

显示 Flutter 通知的回调

当收到推送通知时,可以通过以下代码处理通知的展示逻辑:

PushPortal.instance.setCallbackShowFlutterNotification((message) {
  print("----\nhandle show flutter notification\n----");
  print("data: ${message.data}");

  // 检查通知是否包含 Android 特定数据
  RemoteNotification? notification = message.notification;
  AndroidNotification? android = message.notification?.android;
  if (notification != null && android != null && !kIsWeb) {
    flutterLocalNotificationsPlugin.show(
      notification.hashCode,
      notification.title,
      notification.body,
      NotificationDetails(
        android: AndroidNotificationDetails(
          channel.id,                     // 通道 ID
          channel.name,                   // 通道名称
          channelDescription: channel.description, // 通道描述
          icon: 'launch_background',      // 图标资源路径
        ),
      ),
    );
  }
});

接收推送负载的回调

当接收到推送消息的负载时,可以执行自定义逻辑:

PushPortal.instance.setCallbackReceivePayload((message) {
  print("----\ncallback Receive Payload\n----");
  // 在这里处理消息负载
});

处理初始消息的回调

当应用启动时,可以处理首次加载的消息:

PushPortal.instance.setCallbackInitialMessage((massage) async {
  print("----\ncallback Initial Message\n----");
  WidgetsBinding.instance.addPostFrameCallback((_) async {
    Get.to(const Mailbox()); // 跳转到指定页面
  });
});

调用插件提供的服务

除了回调函数外,pushportal_package 还提供了一些服务方法,用于管理推送通知相关的操作。以下是一些常用的服务方法示例:

获取未读通知数量

通过 unreadCountNotification 方法获取用户的未读通知数量:

final unreadCount = await PushPortal.instance.sevice.unreadCountNotification(
  memberId: 'memberID',       // 用户 ID
  deviceNumber: 'deviceNumber', // 设备编号
);
print("未读通知数量: $unreadCount");

插件支持的功能列表

回调函数列表

  • login()
  • relogin()
  • getFirebaseMessagingToken()
  • setBaseUrl()
  • setCallbackShowFlutterNotification()
  • setCallbackReceivePayload()
  • setCallbackInitialMessage()

服务列表

  • registerTokenMember()
  • getNotificationLog()
  • openedNotification()
  • hideNotification()
  • getNotificationLogDetail()
  • unreadCountNotification()

完整示例代码

以下是一个完整的示例代码,展示了如何使用 pushportal_package 实现推送通知功能:

// ignore_for_file: avoid_print

import 'dart:async';

import 'package:example2/controller.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:get/get.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:pushportal_package/pushportal_package.dart';
import 'app_config.dart';
import 'widgets/alert_button.dart';
import 'widgets/mailbox.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  initializeDateFormatting();
  await PushPortal.instance.initializeApp(
    username: "username",       // 替换为实际用户名
    password: "password",       // 替换为实际密码
    serviceLog: true,           // 开启服务日志
  );
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.yellow,
        fontFamily: 'DBHeaven',
        dialogTheme: DialogTheme(
          alignment: Alignment.center,
          contentTextStyle: Theme.of(context).textTheme.bodyLarge,
        ),
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
      navigatorKey: AppConfig.navigatorKey,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late AndroidNotificationChannel channel;
  bool isFlutterLocalNotificationsInitialized = false;

  /// 初始化 Flutter Local Notifications 插件
  late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

  [@override](/user/override)
  void initState() {
    super.initState();
    prepareData();
    PushPortal.handleReceivePayload.listen((event) async {
      Get.to(const Mailbox());
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    final appWidth = MediaQuery.of(context).size.width;
    final appHeight = MediaQuery.of(context).size.height;
    return Scaffold(
      backgroundColor: AppConfig.primary_color,
      body: Container(
        margin: const EdgeInsets.only(top: 34),
        width: appWidth,
        height: appHeight,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fitWidth,
            image: AssetImage('assets/images/event_copy_2.jpg'),
          ),
        ),
        child: Stack(
          children: [
            Padding(
              padding: const EdgeInsets.only(left: 5, top: 5),
              child: SizedBox(
                width: 50,
                height: 38,
                child: MailboxAlertButton(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> prepareData() async {
    await setupFlutterNotifications();
    await AppController.current.prepareAccessToken();
    await AppController.current.registerFirebaseMessagingToken("memberID");
    await AppController.current.getUnreadCount();

    // 设置通知展示回调
    PushPortal.instance.setCallbackShowFlutterNotification((message) {
      print("----\nhandle show flutter notification\n----");
      print("data: ${message.data}");

      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;
      if (notification != null && android != null && !kIsWeb) {
        flutterLocalNotificationsPlugin.show(
          notification.hashCode,
          notification.title,
          notification.body,
          NotificationDetails(
            android: AndroidNotificationDetails(
              channel.id,               // 通道 ID
              channel.name,             // 通道名称
              channelDescription: channel.description, // 通道描述
              icon: 'launch_background', // 图标资源路径
            ),
          ),
        );
      }
    });

    // 设置接收负载的回调
    PushPortal.instance.setCallbackReceivePayload((message) {
      print("----\ncallback Receive Payload\n----");
    });

    // 设置初始消息的回调
    PushPortal.instance.setCallbackInitialMessage((massage) async {
      print("----\ncallback Initial Message\n----");
      WidgetsBinding.instance.addPostFrameCallback((_) async {
        Get.to(const Mailbox());
      });
    });

    setState(() {});
  }

  Future<void> setupFlutterNotifications() async {
    if (isFlutterLocalNotificationsInitialized) {
      return;
    }
    channel = const AndroidNotificationChannel(
      'high_importance_channel', // 通道 ID
      'High Importance Notifications', // 通道名称
      description: 'This channel is used for important notifications.', // 通道描述
      importance: Importance.high,
    );
    flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

    // 创建 Android 通知通道
    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);
    isFlutterLocalNotificationsInitialized = true;
  }
}

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

1 回复

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


pushportal_package 是一个用于在 Flutter 应用中集成推送通知功能的插件。它可以帮助你轻松地接收和处理推送通知。以下是如何使用 pushportal_package 的基本步骤:

1. 添加依赖

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

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

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

2. 初始化插件

在你的 Flutter 应用中初始化 pushportal_package。通常,你可以在 main.dart 文件中进行初始化:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 PushPortal
  await PushPortal.initialize(
    appId: 'YOUR_APP_ID',  // 替换为你的 App ID
    apiKey: 'YOUR_API_KEY',  // 替换为你的 API Key
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'PushPortal Example',
      home: HomeScreen(),
    );
  }
}

3. 处理推送通知

你可以通过监听推送通知来处理它们。例如,你可以在 HomeScreen 中监听通知:

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

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  String _notificationMessage = 'No notifications yet';

  @override
  void initState() {
    super.initState();
    
    // 监听推送通知
    PushPortal.onNotificationReceived.listen((PushNotification notification) {
      setState(() {
        _notificationMessage = notification.message;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('PushPortal Example'),
      ),
      body: Center(
        child: Text(_notificationMessage),
      ),
    );
  }
}

4. 发送测试通知

你可以通过 PushPortal 提供的 API 发送测试通知:

PushPortal.sendNotification(
  title: 'Test Notification',
  message: 'This is a test notification',
  userId: 'USER_ID',  // 替换为目标用户的 ID
);

5. 处理后台通知

如果你需要在应用处于后台时处理通知,你可以使用 PushPortal 提供的后台处理机制。你可以在 main.dart 中设置后台处理函数:

void backgroundNotificationHandler(PushNotification notification) {
  // 处理后台通知
  print('Background Notification: ${notification.message}');
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 PushPortal
  await PushPortal.initialize(
    appId: 'YOUR_APP_ID',
    apiKey: 'YOUR_API_KEY',
    backgroundHandler: backgroundNotificationHandler,
  );

  runApp(MyApp());
}

6. 处理点击通知

你可以通过监听 PushPortal.onNotificationOpened 来处理用户点击通知的事件:

PushPortal.onNotificationOpened.listen((PushNotification notification) {
  // 处理用户点击通知的事件
  print('Notification clicked: ${notification.message}');
});

7. 获取设备令牌

你可以通过 PushPortal.getDeviceToken 获取设备的推送令牌:

String deviceToken = await PushPortal.getDeviceToken();
print('Device Token: $deviceToken');

8. 注销设备

如果你需要注销设备的推送功能,可以调用 PushPortal.unregister

await PushPortal.unregister();

9. 处理错误

你可以通过监听 PushPortal.onError 来处理推送过程中可能出现的错误:

PushPortal.onError.listen((error) {
  print('PushPortal Error: $error');
});

10. 配置平台特定设置

根据你的应用平台(Android 或 iOS),你可能需要进行一些额外的配置。

Android

AndroidManifest.xml 中添加以下权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

iOS

Info.plist 中添加以下权限:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>
<key>UIBackgroundModes</key>
<array>
  <string>remote-notification</string>
</array>
回到顶部