pusher_websocket_flutter 0.1.1

Pusher Flutter Client #

An unofficial Flutter plugin that wraps pusher-websocket-java on Android and pusher-websocket-swift on iOS.

Get it from pub.

How to install #

  • Add to your pubspec.yaml
dependencies:
  pusher_websocket_flutter: ^0.1.1
  • In /ios/Podfile, set global platform to at least 9.0 platform :ios, '9.0'

For iOS Objective-C based Flutter apps #

It is currently a bit difficult to get some Swift based Flutter plugins working in an Objective-C based Flutter app. See here for info and here for a way to fix.

This set of steps should work to fix this for your project.

  • Add use_frameworks! to the end of the Runner section in /ios/Podfile
  • Set Swift version in your iOS Runner project.
    • Open the project with Xcode.
    • In Runner, File -> New -> File -> Swift File. Name it anything.
    • Xcode will ask you if you wish to create Bridging Header, click yes.
    • Go to Runner Build Settings and set SWIFT_VERSION to either 4.2 or 5.0
    • Delete the Swift file created in step 2
    • Delete the Bridging Header created in step 3
  • flutter clean
  • In /ios pod install --repo-update

If you have trouble, try checking out the example_objc Flutter project.

How to use #

Pusher.init( ... ) #

ParameterTypeDescription
appKeyStringRequired - The application key is a string which is globally unique to your application. It can be found in the API Access section of your application within the Channels user dashboard.
optionsPusherOptionsRequired - The options provided to pusher, more information in the PusherOptions section.
enableLoggingboolOptional - Enabling this will activate the logging of important events to the console.

Pusher.connect( ... ) #

ParameterTypeDescription
onConnectionStateChangeFunction(ConnectionStateChange)Optional - Callback when the state of the connection changes (eg. CONNECTING, CONNECTED, DISCONNECTED, ... ).
onErrorFunction(ConnectionError)Optional - Callback when the connection fires an error (eg. UnauthorizedException).

Pusher.subscribe( ... ) #

ParameterTypeDescription
channelNameStringRequired - provide the channel name to subscribe to (eg. mychannel, private-mychannel or presence-mychannel).

PusherOptions #

ParameterTypeDescription
authPusherAuthOptional - A mechanism for authenticating a user's access to a channel at the point of subscription.
clusterStringOptional - The identifier of the cluster your application was created in. When not supplied, will connect to the mt1(us-east-1) cluster.
hostStringOptional - Provide your own (websocket) host instead of the default ws.pusherapp.com
portintOptional - Provide your own (websocket) port instead of the default 443 (when encryption is enabled) or port 80 (when encryption is disabled).
encryptedboolOptional - Tell pusher to only connect over TLS connections to ensure connection traffic is encrypted. This means using wss:// instead of ws://, encryption is enabled by default.
activityTimeoutintOptional - After this time (in milliseconds) without any messages received from the server, a ping message will be sent to check if the connection is still working. Default value is supplied by the server, low values will result in unnecessary traffic. The default is set to 30000.

PusherAuth #

ParameterTypeDescription
endpointStringRequired - The endpoint pusher should query to make the post request (eg. https://api.example.com/broadcating/auth).
headersMap<String,String>Optional - The headers that should be sent with the POST request to the above endpoint. 2 Different Content-Types are supported: application/x-www-form-urlencoded & application/json. Supplying any of the above types will result into the request body being sent in form-urlencoded format or JSON format. Defaults to {'Content-Type': 'application/x-www-form-urlencoded'}

Development #

Generate the models and the factories: flutter packages pub run build_runner build --delete-conflicting-outputs

0.1.1 #

  • Minor changes to iOS podspec to help with ObjC based apps
  • Documentation update

0.1.0 #

Thanks to GillesMontyne

  • Readme updated with better usage information
  • Support for Pusher's auth system
  • Better configurability in PusherOptions (host, port, encrypted, activityTimeout)

0.0.8 #

  • Update json_annotation and json_serializable

0.0.7 #

  • Run Android callbacks on main thread

0.0.6 #

  • Setting iOS pod as a static framework

0.0.5 #

  • Fixed hot restart resulting in duplicate callbacks

0.0.4 #

  • Fixed calling bind multiple times with the same event name resulting in duplicate callbacks on iOS

0.0.3 #

  • Added return type of void for bind callback

0.0.2 #

  • Small fixes for pub listing

0.0.1 #

  • Initial release with support for channels and events

example/lib/main.dart

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

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

class MyApp extends StatefulWidget {
  @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");

  @override
  void initState() {
    super.initState();
    initPusher();
  }

  Future<void> initPusher() async {
    try {
      await Pusher.init("APP_KEY", PusherOptions(cluster: "us2"), enableLogging: true);
    } on PlatformException catch (e) {
      print(e.message);
    }
  }

  @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(
                        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);
                      },
                    )
                  ],
                ),
              ],
            ),
          )),
    );
  }

  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 ?? ""),
          ],
        ),
      ],
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  pusher_websocket_flutter: ^0.1.1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:pusher_websocket_flutter/pusher.dart';
import 'package:pusher_websocket_flutter/pusher.g.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
74
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
87
Learn more about scoring.

We analyzed this package on Sep 13, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.5.0
  • pana: 0.12.21
  • Flutter: 1.9.1+hotfix.2

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Health suggestions

Format lib/pusher.dart.

Run flutter format to format lib/pusher.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
json_annotation ^3.0.0 3.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.7
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
build_runner ^1.5.2
flutter_test
json_serializable ^3.2.0