pubnub 1.3.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 86

PubNub Dart SDK #

Pub Version

pubnub is a Flutter-friendly SDK written in Dart that allows you to connect to PubNub Data Streaming Network and add real-time features to your application.

Installation #

Using pub dependency management tool #

pubnub uses the standard pub tool for package management to distribute Dart code.

To add the package to your Dart or Flutter project, add pubnub as a dependency in your pubspec.yaml.

dependencies:
  pubnub: ^1.0.0

After adding the dependency to pubspec.yaml, run the pub get command in the root directory of your project (the same that the pubspec.yaml is in).

Using Git #

If you want to use the latest, unreleased version of pubnub, you can add it to pubspec.yaml as a Git package.

dependencies:
  pubnub:
    git: git://github.com/pubnub/dart.git

Using a local copy of the repository #

If you want to copy the Dart repository and modify it locally, clone it using git clone https://github.com/pubnub/dart and then import it into pubspec.yaml as follows:

dependencies:
  pubnub:
    path: ../path-to-cloned-pubnub-repo

Importing #

After you install the pubnub package, import it in your application. You can import it in one of two ways:

// Import all PubNub objects into your namespace
import 'package:pubnub/pubnub.dart';

// Or import PubNub into a named namespace
import 'package:pubnub/pubnub.dart' as pn;

Usage #

Keyset #

First, create a Keyset instance:

final myKeyset = Keyset(
  subscribeKey: 'demo',
  publishKey: 'demo',
  uuid: UUID('demo'));

Keyset contains all your configuration. You can use multiple Keysets (with different parameters) if you need.

If you have a PubNub account, replace demo with the key values from your PubNub dashboard. If you don't, you can use the highly rate-limited demo keys, but be aware that the keyset is public, so don't send any sensitive data.

PubNub instance #

Next, instantiate the PubNub class, passing myKeyset as a default keyset. This will be used any time a keyset is not passed into a method.

final pubnub = PubNub(defaultKeyset: myKeyset);

Now you can use the pubnub instance to publish messages, subscribe to channels, and everything else!

Publishing messages #

To publish a message, use the publish method.

pubnub.publish('my_channel', { 'content': 'Hello world!' });

Messages can be any JSON-serializable object.

If you are going to publish a lot of messages to one channel, you can use channel abstraction to obtain an instance of a Channel.

final myChannel = pubnub.channel('my_channel');

myChannel.publish(200);
myChannel.publish({ 'answer': 42 });

Subscribing to channels #

To subscribe to a list of channels or channel groups, use the subscribe method. You need to pass a Set of channels or channel groups.

var subscription = pubnub.subscribe(channels: {'ch1', 'ch2'});

You can also use your Channel instance:

var subscription = myChannel.subscribe();

Both of those methods return a Subscription.

A Subscription contains a Dart Stream messages from the channel(s) to which you are subscribed. You can transform that stream in the usual ways, or add a listener using listen:

subscription.messages.listen((envelope) {
  print(`${envelope.uuid} sent a message: ${envelope.payload}`);
});

var envelope =
      await sub.messages.firstWhere((envelope) => envelope.channel == 'ch2');

Channel history #

You can retrieve past messages from a channel in two ways, as follows:

Using channel.history

Use this method if you want to fetch messages gradually. They are fetched in descending order (from newest to oldest) by default.

var history = myChannel.history(chunkSize: 50);

await history.more();
print(history.messages.length); // 50
await history.more();
print(history.messages.length); // 100

Using channel.messages

Use this method to fetch many messages at once.

var history = myChannel.messages(from: Timetoken(1234567890));

var count = await history.count();
print(count);

var messages = await history.fetch();
print(messages.length);

await history.delete(); // Beware! This will delete all messages matched

Multiple keysets #

There are two ways to use multiple keysets at the same time, as follows:

Using named keysets

You can add multiple keysets with a name to an instance of PubNub.

pubnub.keysets.add(myKeyset1, name: 'keyset1');
pubnub.keysets.add(myKeyset2, name: 'keyset2');

To use a named keyset instead of the default, pass its name in a using: parameter into one of the pubnub instance methods:

pubnub.publish('channel', 42, using: 'keyset1');
var myChannel = pubnub.channel('channel', using: 'keyset2');

Using a keyset instance

Instead of adding the keyset to pubnub.keysets, you can use the keyset: named parameter to pass a keyset instance directly to pubnub instance methods:

pubnub.subscribe(channels: {'channel'}, keyset: myKeyset1)

Contributing #

  1. Clone the repository.

     git clone https://github.com/pubnub/dart.git
    
  2. Enter the directory and install dependencies.

     cd dart
     pub get
    
  3. Run the build_runner to generate necessary source files.

     pub run build_runner build
    

v1.3.0 #

June 25 2020

Full Changelog

  • 🌟️ Add message encryption support.

v1.2.0 #

June 10 2020

Full Changelog

  • 🌟️ Add simplified Objects API support with UUID and Channel metadata / membership management.
  • 🐛 Fixes missing PushGateway type support of fcm for Push Notification.

v1.1.3 #

May 11 2020

  • 🐛 Fixes unsubscribeAll so its no longer modifying subscription list during iteration. Fixed the following issues reported by @pushpendraKh: #6.
  • 🐛 Fixes exports to include presence and channel group results.

v1.1.2 #

May 6 2020

Full Changelog

  • 🐛 Fixes issues of missing types for objects and push-notification. Fixed the following issues reported by @pushpendraKh: #5.

v1.1.1 #

May 6 2020

Full Changelog

  • 🐛 Expose missing types.

v1.1.0 #

May 5 2020

Full Changelog

  • ⭐️️ Bumps cbor package version and fixes analyzer warnings.
  • ⭐️️ Removes many dependencies that are unnecessary.
  • ⭐️️ Build_runner is no longer necessary to use.
  • 🐛 Refactors logging to rely on Zones.
  • 🐛 Fixes issues with resubscribing and improves injectLogger.

v1.0.5 #

May 4 2020

  • 🐛 Fix wrong API Uri in Push Notifications. Fixed the following issues reported by @aadil058: #2.
  • 🐛 Fix Subscription.unsubscribe to correctly close the messages stream. Fixed the following issues reported by @are: #3.

v1.0.4 #

April 27 2020

  • 🌟️ Add HereNow to PresenceDx, usable as pubnub.hereNow().
  • 🐛 Fix subscribe withPresence: true not properly forwarding messages when used with wildcard channels.

v1.0.3 #

April 22 2020

  • ⭐️️ Fix a typo in UserDx docstring.
  • 🐛 Change all Symbols to Strings to support Flutter better, fix a typo in SubscribeParams preventing subscribe from working.

v1.0.2 #

April 18 2020

Full Changelog

  • ⭐️️ Add backward synchronization to private repository for pubspec.yaml and lib/src/core/core.dart.
  • ⭐️️ Prevent tests from breaking when version is bumped.

v1.0.1 #

April 18 2020

Full Changelog

  • ⭐️️ Refactor PAM, hide logger instances and clean up tests.
  • ⭐️️ Add package:pedantic config to analysis, fix lint issues.
  • ⭐️️ Removes dummy changelog entry.
  • ⭐️️ Add simple example.
  • ⭐️️ Improve package description.
  • ⭐️️ Clean up test prefixes.
  • 🐛 Ensure()isEqual now uses correct template.
  • 🐛 Add PAM to library exports.
  • 🐛 Consistently use PubNubversion in tests.

v1.0.0 #

April 15 2020

  • 🌟️ Add ability to fetch current PubNub timetoken.
  • 🌟️ Add ability to publish messages and signals to channels and channel groups.
  • 🌟️ Add ability to subscribe to channels and channel groups.
  • 🌟️ Add ability to manage Objects (Spaces, Users and Memberships).
  • 🌟️ Add ability to manage PubNub Access Manager.
  • 🌟️ Add ability to manage device registration for Push Notification Service.
  • 🌟️ Add ability to add, delete and retrieve message actions.
  • 🌟️ Add channel and channel group abstractions to allow using History.

example/example.dart

import 'package:pubnub/pubnub.dart';

void main() async {
  // Create PubNub instance with default keyset.
  var pubnub = PubNub(
      defaultKeyset:
          Keyset(subscribeKey: 'demo', publishKey: 'demo', uuid: UUID('demo')));

  // Subscribe to a channel
  var subscription = await pubnub.subscribe(channels: {'test'});

  subscription.messages.take(1).listen((message) {
    print(message);
  });

  // Publish a message
  await pubnub.publish('test', {'message': 'My message!'});

  // Unsubscribe
  await subscription.unsubscribe();

  // Channel abstraction for easier usage
  var channel = pubnub.channel('test');

  await channel.publish({'message': 'Another message'});

  // Work with channel History API
  var history = channel.messages();
  var count = await history.count();

  print('Messages on test channel: $count');
}

Use this package as a library

1. Depend on it

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


dependencies:
  pubnub: ^1.3.0

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or 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:pubnub/pubnub.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
71
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]
86
Learn more about scoring.

We analyzed this package on Jul 11, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.15

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.6.0 <3.0.0
cbor ^3.1.0 3.2.0
convert ^2.0.0 2.1.1
crypto ^2.1.0 2.1.5
dio ^3.0.0 3.0.9
encrypt ^4.0.2 4.0.2
meta ^1.1.0 1.2.2 1.3.0-nullsafety
pool ^1.4.0 1.4.0
Transitive dependencies
args 1.6.0
asn1lib 0.6.5
async 2.4.2
charcode 1.1.3
clock 1.0.1
collection 1.14.13 1.15.0-nullsafety
http_parser 3.1.4
path 1.7.0
pointycastle 1.0.2
source_span 1.7.0
stack_trace 1.9.5
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.2.0 1.3.0-nullsafety
Dev dependencies
pedantic 1.9.0
test 1.11.1
test_coverage 0.4.1