Flutter实时消息推送插件flutter_pusher的使用

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

Flutter实时消息推送插件flutter_pusher的使用

概述

flutter_pusher 是一个非官方的 Flutter 插件,它通过封装 pusher-websocket-java(Android)和 pusher-websocket-swift(iOS)来实现跨平台的实时消息推送功能。此插件可以帮助开发者快速集成 Pusher 的实时通信能力到他们的 Flutter 应用中。

注意:此插件仍处于开发阶段,部分 API 可能尚未完全可用。欢迎反馈问题或提交 PR!


如何安装

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

    dependencies:
      flutter_pusher: ^1.0.2
  2. 对于 iOS 项目:

    • 打开 /ios/Podfile 文件,并确保设置全局平台为至少 9.0:
      platform :ios, '9.0'
    • 如果你的 Flutter 应用基于 Objective-C,可能需要一些额外配置以支持 Swift 插件。具体步骤如下:
      • /ios/Podfile 中添加 use_frameworks!
      • 设置 Swift 版本:
        • 打开 Xcode,创建一个 Swift 文件并选择默认版本(如 4.2 或 5.0)。
        • 删除创建的 Swift 文件及其对应的桥接头文件。
      • 运行以下命令清理和重新安装依赖:
        flutter clean
        cd ios && pod install --repo-update

如何使用

初始化 Pusher

首先需要调用 Pusher.init() 方法初始化 Pusher 实例。参数包括应用密钥 (appKey) 和其他可选选项 (PusherOptions)。

await Pusher.init(
  "APP_KEY", // 替换为你的 Pusher 应用密钥
  PusherOptions(
    cluster: "eu", // 指定集群
  ),
  enableLogging: true, // 启用日志记录
);
建立连接

使用 Pusher.connect() 方法建立与 Pusher 服务器的连接。可以传入回调函数监听连接状态变化和错误事件。

Pusher.connect(
  onConnectionStateChange: (x) async {
    if (mounted) {
      setState(() {
        lastConnectionState = x.currentState;
      });
    }
  },
  onError: (x) {
    debugPrint("Error: ${x.message}");
  },
);
订阅频道

通过 Pusher.subscribe() 方法订阅频道。频道名称可以是普通频道(my-channel)、私有频道(private-mychannel)或存在频道(presence-mychannel)。

channel = await Pusher.subscribe("my-channel");
解绑频道

如果不再需要监听某个频道,可以通过 Pusher.unsubscribe() 方法解绑频道。

await Pusher.unsubscribe("my-channel");
channel = null;
绑定事件

使用 channel.bind() 方法绑定特定事件的回调函数。当接收到事件时,会触发回调函数。

await channel.bind("my-event", (x) {
  if (mounted) {
    setState(() {
      lastEvent = x;
    });
  }
});
触发事件

通过 channel.trigger() 方法向频道发送自定义事件。

await channel.trigger("client-trigger", data: {
  "testValue": 123,
  "anotherOne": false,
  "nested": {"w0t": "m8"}
});
断开连接

使用 Pusher.disconnect() 方法断开与 Pusher 服务器的连接。

Pusher.disconnect();

示例代码

以下是完整的示例代码,展示如何使用 flutter_pusher 插件实现实时消息推送功能:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_pusher/pusher.dart';

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

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

class _MyAppState extends State<MyApp> {
  Event lastEvent;
  String lastConnectionState;
  Channel channel;

  var channelController = TextEditingController(text: "my-channel");
  var eventController = TextEditingController(text: "my-event");
  var triggerController = TextEditingController(text: "client-trigger");

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

  Future<void> initPusher() async {
    try {
      await Pusher.init(
          "APP_KEY", // 替换为你的 Pusher 应用密钥
          PusherOptions(
            cluster: "eu",
          ),
          enableLogging: true);
    } on PlatformException catch (e) {
      print(e.message);
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Pusher 实时消息推送示例'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              _buildInfo(),
              RaisedButton(
                child: Text("连接"),
                onPressed: () {
                  Pusher.connect(
                    onConnectionStateChange: (x) async {
                      if (mounted)
                        setState(() {
                          lastConnectionState = x.currentState;
                        });
                    },
                    onError: (x) {
                      debugPrint("Error: ${x.message}");
                    },
                  );
                },
              ),
              RaisedButton(
                child: Text("断开连接"),
                onPressed: () {
                  Pusher.disconnect();
                },
              ),
              Row(
                children: <Widget>[
                  Container(
                    width: 200,
                    child: TextField(
                      autocorrect: false,
                      controller: channelController,
                      decoration: InputDecoration(hintText: "频道名"),
                    ),
                  ),
                  RaisedButton(
                    child: Text("订阅"),
                    onPressed: () async {
                      channel = await Pusher.subscribe(channelController.text);
                    },
                  )
                ],
              ),
              Row(
                children: <Widget>[
                  Container(
                    width: 200,
                    child: TextField(
                      controller: channelController,
                      decoration: InputDecoration(hintText: "频道名"),
                    ),
                  ),
                  RaisedButton(
                    child: Text("取消订阅"),
                    onPressed: () async {
                      await Pusher.unsubscribe(channelController.text);
                      channel = null;
                    },
                  )
                ],
              ),
              Row(
                children: <Widget>[
                  Container(
                    width: 200,
                    child: TextField(
                      controller: eventController,
                      decoration: InputDecoration(hintText: "事件名"),
                    ),
                  ),
                  RaisedButton(
                    child: Text("绑定事件"),
                    onPressed: () async {
                      await channel.bind(eventController.text, (x) {
                        if (mounted)
                          setState(() {
                            lastEvent = x;
                          });
                      });
                    },
                  )
                ],
              ),
              Row(
                children: <Widget>[
                  Container(
                    width: 200,
                    child: TextField(
                      controller: eventController,
                      decoration: InputDecoration(hintText: "事件名"),
                    ),
                  ),
                  RaisedButton(
                    child: Text("解绑事件"),
                    onPressed: () async {
                      await channel.unbind(eventController.text);
                    },
                  )
                ],
              ),
              Row(
                children: <Widget>[
                  Container(
                    width: 200,
                    child: TextField(
                      controller: triggerController,
                      decoration: InputDecoration(hintText: "触发事件名"),
                    ),
                  ),
                  RaisedButton(
                    child: Text("触发事件"),
                    onPressed: () async {
                      await channel.trigger(triggerController.text, data: {
                        "testValue": 123,
                        "anotherOne": false,
                        "nested": {"w0t": "m8"}
                      });
                    },
                  )
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildInfo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              "连接状态: ",
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            Text(lastConnectionState ?? "未知"),
          ],
        ),
        SizedBox(height: 8),
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              "最后事件频道: ",
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            Text(lastEvent?.channel ?? ""),
          ],
        ),
        SizedBox(height: 8),
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              "最后事件名称: ",
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            Text(lastEvent?.event ?? ""),
          ],
        ),
        SizedBox(height: 8),
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              "最后事件数据: ",
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            Text(lastEvent?.data ?? ""),
          ],
        ),
      ],
    );
  }
}

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

1 回复

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


flutter_pusher 是一个用于在 Flutter 应用中实现实时消息推送的插件,它基于 Pusher 服务。Pusher 是一个提供实时消息传递服务的平台,允许你通过 WebSocket 实现实时通信。

1. 安装 flutter_pusher 插件

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

dependencies:
  flutter:
    sdk: flutter
  flutter_pusher: ^2.0.0

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

2. 初始化 Pusher

在你的 Dart 文件中导入 flutter_pusher 并初始化 Pusher:

import 'package:flutter_pusher/flutter_pusher.dart';

final pusher = FlutterPusher(
  "YOUR_APP_KEY",
  PusherOptions(
    cluster: "YOUR_CLUSTER",
    encrypted: true,
  ),
);

YOUR_APP_KEYYOUR_CLUSTER 替换为你从 Pusher 控制台获取的实际值。

3. 连接 Pusher

在初始化 Pusher 后,你需要连接它:

pusher.connect();

4. 订阅频道和绑定事件

你可以订阅一个频道并绑定事件监听器来接收消息:

final channel = pusher.subscribe("my-channel");

channel.bind("my-event", (event) {
  print("Received event: ${event.data}");
});

5. 处理消息

当事件被触发时,你可以在回调函数中处理接收到的消息:

channel.bind("my-event", (event) {
  print("Event data: ${event.data}");
  // 在这里处理你的业务逻辑
});

6. 断开连接

当你不再需要 Pusher 连接时,可以断开连接:

pusher.disconnect();

7. 完整示例

以下是一个完整的示例代码:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Pusher Demo',
      home: PusherDemo(),
    );
  }
}

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

class _PusherDemoState extends State<PusherDemo> {
  late FlutterPusher pusher;

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

    pusher = FlutterPusher(
      "YOUR_APP_KEY",
      PusherOptions(
        cluster: "YOUR_CLUSTER",
        encrypted: true,
      ),
    );

    pusher.connect();

    final channel = pusher.subscribe("my-channel");

    channel.bind("my-event", (event) {
      print("Received event: ${event.data}");
      // 在这里处理你的业务逻辑
    });
  }

  [@override](/user/override)
  void dispose() {
    pusher.disconnect();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Pusher Demo'),
      ),
      body: Center(
        child: Text('Listening for Pusher events...'),
      ),
    );
  }
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!