You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中搭配使用Pusher和Awesome Notifications插件

Flutter 中 Pusher 与 Awesome Notifications 联动实现方案

1. 基础依赖引入

在pubspec.yaml中添加以下依赖,完成后执行flutter pub get:

  • pusher_flutter(替代原flutter_pusher的官方维护版本,稳定性更高)
  • awesome_notifications

2. 初始化两个服务

首先在应用启动时(比如main函数的runApp之前)完成Awesome Notifications的初始化,示例代码:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // 初始化Awesome Notifications
  await AwesomeNotifications().initialize(
    'resource://drawable/res_app_icon', // 替换为你的应用通知图标路径
    [
      NotificationChannel(
        channelKey: 'pusher_notification_channel',
        channelName: 'Pusher推送通知',
        channelDescription: '接收Pusher服务推送的通知',
        importance: NotificationImportance.Max,
        channelShowBadge: true,
      )
    ],
  );
  // 后续添加Pusher初始化逻辑
  runApp(const MyApp());
}

之后完成Pusher客户端的初始化,同时绑定事件监听:

// 初始化Pusher客户端
PusherClient pusher = PusherClient(
  '你的Pusher APP_KEY',
  PusherOptions(
    cluster: '你的Pusher集群区域',
  ),
  autoConnect: false,
);

// 绑定连接状态监听
pusher.onConnectionStateChange((state) {
  if (state?.currentState == ConnectionState.connected) {
    // 连接成功后订阅你需要监听的频道
    Channel channel = pusher.subscribe('你的目标频道名');
    // 绑定对应事件的回调,这里就是联动的核心逻辑
    channel.bind('你的事件名称', (event) {
      // 收到Pusher推送的事件数据后,触发Awesome Notifications展示本地通知
      if (event?.data != null) {
        // 解析事件数据,根据你的业务自定义内容
        Map<String, dynamic> notificationData = jsonDecode(event!.data.toString());
        AwesomeNotifications().createNotification(
          content: NotificationContent(
            id: DateTime.now().millisecondsSinceEpoch ~/ 1000, // 保证通知ID唯一
            channelKey: 'pusher_notification_channel',
            title: notificationData['title'],
            body: notificationData['body'],
            payload: notificationData, // 可以携带自定义数据用于点击跳转
          ),
        );
      }
    });
  }
});

// 触发Pusher连接
pusher.connect();

3. 必要配置注意项

  • 提前申请通知权限:在应用启动后调用AwesomeNotifications().requestPermissionToSendNotifications(),获取用户的通知授权
  • 安卓端需要在AndroidManifest.xml中配置Awesome Notifications要求的相关权限,以及通知渠道的配置
  • 如果需要处理用户点击通知的跳转逻辑,可通过Awesome Notifications的actionStream监听通知点击事件,配合payload里的自定义参数实现页面跳转

内容的提问来源于stack exchange,提问作者Igor Lopatchin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 09:45:09