Flutter消息推送插件my_flutter_pusher的使用

Flutter消息推送插件my_flutter_pusher的使用

如何安装

  1. 在你的pubspec.yaml文件中添加以下依赖:
dependencies:
  my_flutter_pusher: ^1.0.2
  1. /ios/Podfile中设置全局平台至少为9.0:
    platform :ios, '9.0'
    

对于iOS Objective-C基于的Flutter应用

目前,在Objective-C基础上的Flutter应用中使用一些Swift基础的Flutter插件可能有些困难。你可以参考以下步骤来解决这个问题:

  1. /ios/Podfile的Runner部分末尾添加use_frameworks!

    use_frameworks!
    
  2. 设置你的iOS Runner项目的Swift版本。

    • 打开项目并用Xcode打开。
    • 在Runner中,选择File -> New -> File -> Swift File,命名它为任意名称。
    • Xcode会询问你是否要创建桥接头文件,点击“是”。
    • 前往Runner的Build Settings,将SWIFT_VERSION设置为4.2或5.0。
    • 删除在步骤2中创建的Swift文件。
    • 删除在步骤3中创建的桥接头文件。
  3. 运行flutter clean

  4. /ios目录下运行pod install --repo-update

如何使用

Pusher.init(...)
参数 类型 描述
appKey String 必须 - 应用程序密钥是一个全局唯一的字符串,可以在Channels用户仪表板的应用程序API访问部分找到。
options PusherOptions 必须 - 提供给Pusher的选项,更多信息见PusherOptions部分。
enableLogging bool 可选 - 启用此功能将在控制台上激活重要事件的日志记录。
Pusher.connect(...)
参数 类型 描述
onConnectionStateChange Function(ConnectionStateChange) 可选 - 当连接状态发生变化时的回调(例如,CONNECTINGCONNECTEDDISCONNECTED等)。
onError Function(ConnectionError) 可选 - 当连接发生错误时的回调(例如,UnauthorizedException)。
Pusher.subscribe(...)
参数 类型 描述
channelName String 必须 - 提供要订阅的频道名称(例如,mychannelprivate-mychannelpresence-mychannel)。
PusherOptions
参数 类型 描述
auth PusherAuth 可选 - 一种在订阅频道时验证用户访问机制的方法。
cluster String 可选 - 您的应用程序创建的集群标识符。如果不提供,则连接到mt1(us-east-1)集群。
host String 可选 - 提供自己的(WebSocket)主机而不是默认的ws.pusherapp.com
port int 可选 - 提供自己的(WebSocket)端口而不是默认的443(加密启用时)或端口80(加密禁用时)。
encrypted bool 可选 - 告诉Pusher仅通过TLS连接进行连接以确保连接流量被加密。这意味着使用wss://而不是ws://,加密默认启用。
activityTimeout int 可选 - 在没有从服务器收到任何消息的时间(以毫秒为单位)之后发送ping消息以检查连接是否仍然工作。默认值由服务器提供,低值会导致不必要的流量。默认值为30000
PusherAuth
参数 类型 描述
endpoint String 必须 - Pusher应该查询以发起POST请求的端点(例如,https://api.example.com/broadcating/auth)。
headers Map<String,String> 可选 - 发送到上述端点的POST请求的头部。支持两种不同的Content-Typesapplication/x-www-form-urlencodedapplication/json。提供上述任何类型将导致请求体以form-urlencoded格式或JSON格式发送。默认值为{'Content-Type': 'application/x-www-form-urlencoded'}

示例代码

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:my_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(
          "YOUR_APP_KEY",
          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('Plugin example app'),
          ),
          body: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                _buildInfo(),
                RaisedButton(
                  child: Text("Connect"),
                  onPressed: () {
                    Pusher.connect(onConnectionStateChange: (x) async {
                      if (mounted)
                        setState(() {
                          lastConnectionState = x.currentState;
                        });
                    }, onError: (x) {
                      debugPrint("Error: ${x.message}");
                    });
                  },
                ),
                RaisedButton(
                  child: Text("Disconnect"),
                  onPressed: () {
                    Pusher.disconnect();
                  },
                ),
                Row(
                  children: <Widget>[
                    Container(
                      width: 200,
                      child: TextField(
                        autocorrect: false,
                        controller: channelController,
                        decoration: InputDecoration(hintText: "Channel"),
                      ),
                    ),
                    RaisedButton(
                      child: Text("Subscribe"),
                      onPressed: () async {
                        channel =
                            await Pusher.subscribe(channelController.text);
                      },
                    )
                  ],
                ),
                Row(
                  children: <Widget>[
                    Container(
                      width: 200,
                      child: TextField(
                        controller: channelController,
                        decoration: InputDecoration(hintText: "Channel"),
                      ),
                    ),
                    RaisedButton(
                      child: Text("Unsubscribe"),
                      onPressed: () async {
                        await Pusher.unsubscribe(channelController.text);
                        channel = null;
                      },
                    )
                  ],
                ),
                Row(
                  children: <Widget>[
                    Container(
                      width: 200,
                      child: TextField(
                        controller: eventController,
                        decoration: InputDecoration(hintText: "Event"),
                      ),
                    ),
                    RaisedButton(
                      child: Text("Bind"),
                      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: "Event"),
                      ),
                    ),
                    RaisedButton(
                      child: Text("Unbind"),
                      onPressed: () async {
                        await channel.unbind(eventController.text);
                      },
                    )
                  ],
                ),
                Row(
                  children: <Widget>[
                    Container(
                      width: 200,
                      child: TextField(
                        controller: triggerController,
                        decoration: InputDecoration(hintText: "Trigger"),
                      ),
                    ),
                    RaisedButton(
                      child: Text("Trigger"),
                      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(
              "Connection State: ",
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            Text(lastConnectionState ?? "Unknown"),
          ],
        ),
        SizedBox(height: 8),
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              "Last Event Channel: ",
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            Text(lastEvent?.channel ?? ""),
          ],
        ),
        SizedBox(height: 8),
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              "Last Event Name: ",
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            Text(lastEvent?.event ?? ""),
          ],
        ),
        SizedBox(height: 8),
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              "Last Event Data: ",
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            Text(lastEvent?.data ?? ""),
          ],
        ),
      ],
    );
  }
}

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

1 回复

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


my_flutter_pusher 是一个用于在 Flutter 应用中集成 Pusher 消息推送服务的插件。Pusher 是一个实时消息推送服务,允许开发者在应用中轻松实现实时功能,如聊天、通知、实时数据更新等。

以下是如何在 Flutter 项目中使用 my_flutter_pusher 插件的基本步骤:

1. 添加依赖

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

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

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

2. 初始化 Pusher

在你的 Dart 文件中,导入 my_flutter_pusher 插件并初始化 Pusher:

import 'package:my_flutter_pusher/my_flutter_pusher.dart';

void initPusher() {
  Pusher.init(
    "YOUR_PUSHER_APP_KEY",
    PusherOptions(
      cluster: "YOUR_PUSHER_APP_CLUSTER",
      encrypted: true,
    ),
  );
}

YOUR_PUSHER_APP_KEYYOUR_PUSHER_APP_CLUSTER 替换为你在 Pusher 控制台中获取的实际值。

3. 连接到 Pusher

初始化后,连接到 Pusher 服务:

void connectToPusher() {
  Pusher.connect(
    onConnectionStateChange: (state) {
      print("Connection state changed: $state");
    },
    onError: (error) {
      print("Error: $error");
    },
  );
}

4. 订阅频道

连接到 Pusher 后,你可以订阅一个频道来接收消息:

void subscribeToChannel() {
  Pusher.subscribe(
    channelName: "my-channel",
    onEvent: (event) {
      print("Event received: ${event.eventName}, Data: ${event.data}");
    },
  );
}

5. 处理事件

在订阅的频道中,你可以监听特定的事件并处理它们:

void listenToEvent() {
  Pusher.bind(
    eventName: "my-event",
    callback: (data) {
      print("Event data: $data");
    },
  );
}

6. 断开连接

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

void disconnectFromPusher() {
  Pusher.disconnect();
}

7. 完整示例

以下是一个完整的示例,展示了如何初始化、连接、订阅和处理 Pusher 事件:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: PusherExample(),
    );
  }
}

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

class _PusherExampleState extends State<PusherExample> {
  [@override](/user/override)
  void initState() {
    super.initState();
    initPusher();
  }

  void initPusher() {
    Pusher.init(
      "YOUR_PUSHER_APP_KEY",
      PusherOptions(
        cluster: "YOUR_PUSHER_APP_CLUSTER",
        encrypted: true,
      ),
    );

    connectToPusher();
  }

  void connectToPusher() {
    Pusher.connect(
      onConnectionStateChange: (state) {
        print("Connection state changed: $state");
      },
      onError: (error) {
        print("Error: $error");
      },
    );

    subscribeToChannel();
  }

  void subscribeToChannel() {
    Pusher.subscribe(
      channelName: "my-channel",
      onEvent: (event) {
        print("Event received: ${event.eventName}, Data: ${event.data}");
      },
    );

    listenToEvent();
  }

  void listenToEvent() {
    Pusher.bind(
      eventName: "my-event",
      callback: (data) {
        print("Event data: $data");
      },
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Pusher Example"),
      ),
      body: Center(
        child: Text("Pusher integration example"),
      ),
    );
  }

  [@override](/user/override)
  void dispose() {
    Pusher.disconnect();
    super.dispose();
  }
}
回到顶部